基于jquery-resizable创建可调整大小的表(table)格

 更新时间:2023年06月15日 00:09:42   作者:webkaka  
本文介绍如何基于jquery-resizable实现可调整表格(table)列宽的代码,需要的朋友可以参考下
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

本文介绍如何使用jquery-resizable调整表格(table)列宽。

效果图

在线演示 下载地址

示例介绍

鼠标拖动单元格边框,可调整列宽。

创建可调整大小的列需要付出一些额外的努力,因为表没有一种简单的方法来创建可以移动的拖动句柄。

为了调整列的大小,我们可以在列的右侧添加一个元素来提供句柄,这样我们就有了一个用于拖动的视觉指示器。要调整大小的表格单元格为 position:relative,注入的元素为 position:absolute 并推到单元格右侧以提供拖动手柄。拖动然后简单地调整单元格的大小。

在实践中,这意味着你需要一些CSS(或jquery样式)来强制注入样式和逻辑来注入元素。

HTML

<table>
    <thead>
        <th> col 1 </th>
        <th> col 2 </th>
        <th> col 3 </th>
        <th> col 4 </th>
    </thead>
    <tbody>
        <tr>
            <td> Column 1 </td>
            <td> Column 2 </td>
            <td> Column 3 </td>
            <td> Column 4 </td>
        </tr>
        <tr>
            <td> Column 1 </td>
            <td> Column 2 </td>
            <td> Column 3 </td>
            <td> Column 4 </td>
        </tr>
    </tbody>
</table>

html的table标签为常规结构,不需要添加额外的ID属性或class属性。

jQuery

jQuery编程需要先引用jQuery库文件,以及jquery-resizable.js插件。

<script src='jquery-3.2.1.min.js'></script>
<script src='jquery-resizable.js'></script>
<script>
$("td:first-child,td:nth-child(2),td:nth-child(3),th:first-child,th:nth-child(2),th:nth-child(3)").css({position: "relative" }).prepend("<div class='resizer'></div>").resizable({
  resizeHeight: false,
  handleSelector: "",
  onDragStart: function (e, $el, opt) {
    if (!$(e.target).hasClass("resizer"))
    return false;
    return true;
  } });
</script>

上面的jQuery实现代码,加上注释文字,你可能更容易理解:

//$("td,th")
$("td:first-child,td:nth-child(2),td:nth-child(3),th:first-child,th:nth-child(2),th:nth-child(3)").
css({
  /* 需要包含 resizer */
  position: "relative" })
/* 检查 .resizer CSS */.
prepend("<div class='resizer'></div>").
resizable({
  resizeHeight: false,
  // 通过 .resizer 元素,使用列作为句柄和筛选器
  handleSelector: "",
  onDragStart: function (e, $el, opt) {
    // 只拖拽 resizer
    if (!$(e.target).hasClass("resizer"))
    return false;
    return true;
  } });

总结

本文介绍了使用jquery-resizable拖动单元格边框调整表格(table)列宽的方法,需要该效果的朋友可以直接下载源码使用。

相关文章

最新评论

?


http://www.vxiaotou.com