使用jqueryUI实现自由调整表格列宽

  今天项目中需要插入表格,用Excel表格调整列宽时,想怎么拖就怎么拖,于是乎就让插入的表格也这么让人舒服。网上查找许久,没找到好用的方案。最后发现jQuery UI中的resizable()方法可以实现div的自由调整,既然可以在div上实现,那表格也应该没问题吧。于是就动手折腾,成功搞定。

代码详情:

main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>表格列宽调整</title>
<link rel="stylesheet" href="${pageContext.request.contextPath }/css/jquery-ui.css">
<link rel="stylesheet" href="${pageContext.request.contextPath }/css/bootstrap.css">
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath }/js/jquery-ui.js"></script>

<style type="text/css">
    .tab_info {
        font-size: 13px;
        table-layout: fixed;
    }
    .tab_info th {
        background-color: #f5f5f5;    
    }
    .tab_info td {
     white-space: nowrap; overflow: hidden; } .ui-resizable { background-color: #fff; } </style> <script type="text/javascript"> $(function() { $("th").resizable(); //调用方法,实现可自由调整 }); </script> </head> <body> <table class="table table-bordered tab_info"> <thead> <tr> <th>商品编号</th> <th>商品名称</th> <th>品牌</th> <th>型号</th> <th>规格</th> <th>单位</th> <th>进货价</th> <th>库存数量</th> <th>销售价格</th> </tr> </thead> <tbody> <tr> <td>1051181502</td> <td>碧根果</td> <td>自产</td> <td>123</td> <td>1*500g</td> <td></td> <td>10</td> <td>10</td> <td>20</td> </tr> </tbody> </table> </body> </html>

实现功能需引入jquery-ui.js 和 jquery-ui.css,因为resizable()方法会生成调用相应的class样式。

效果图如下:

为table加上 table-layout: fixed; 并为td加上overflow: hidden; 可实现隐藏列中超出内容。

调整功能是实现了,不过右下角的这个小三角就看着让人整个就不好了。于是查看源码,发现调用了resizable()之后是在th中生成了三个div,最后一个就是小三角的样式。

通过js移除方式:$("th > div:last-child").removeClass();

另外通过分析resizable()的源码实现,也可以直接修改源码移除小三角。

在jquery-ui.js中找到下面这段,将classes删除或将值置空即可。最后小三角就没了。

"ui-resizable-se":""
$.widget( "ui.resizable", $.ui.mouse, {
    version: "1.12.1",
    widgetEventPrefix: "resize",
    options: {
        alsoResize: false,
        animate: false,
        animateDuration: "slow",
        animateEasing: "swing",
        aspectRatio: false,
        autoHide: false,
        classes: {
            "ui-resizable-se": "ui-icon ui-icon-gripsmall-diagonal-se"
        },
posted @ 2018-09-14 17:55  hello龙兄  阅读(3039)  评论(0编辑  收藏  举报