今天項目中需要插入表格,用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" },