直接上代碼吧,原理可以看我上一篇博文。本實現基於jquery,完美實現拖動改變表格的列大小功能,只需將代碼放置在你頁面的底部即可(jquery必須先引入)。
$(function () { var isMouseDown = false; var currentTh = null; $('table th').bind({ mousedown:function (e) { var $th = $(this); var left = $th.offset().left; //元素距左 var rightPos = left + $th.outerWidth(); if (rightPos-4<= e.pageX && e.pageX <= rightPos) { isMouseDown = true; currentTh = $th; $('table th').css('cursor','ew-resize'); //創建遮罩層,防止mouseup事件被其它元素阻止冒泡,導致mouseup事件無法被body捕獲,導致拖動不能停止 var bodyWidth = $('body').width(); var bodyHeight = $('body').height(); $('body').append('<div id="mask" style="opacity:0;top:0px;left:0px;cursor:ew-resize;background-color:green;position:absolute;z-index:9999;width:'+bodyWidth+'px;height:'+bodyHeight+'px;"></div>'); } } }); $('body').bind({ mousemove:function(e) { //移動到column右邊緣提示 $('table th').each(function (index,eleDom) { var ele = $(eleDom); var left = ele.offset().left; //元素距左 var rightPos = left + ele.outerWidth(); if (rightPos-4<= e.pageX && e.pageX <= rightPos) { //移到列右邊緣 ele.css('cursor','ew-resize'); }else{ if(!isMouseDown){ //不是鼠標按下的時候取消特殊鼠標樣式 ele.css("cursor","auto"); } } }); //改變大小 if(currentTh != null){ if(isMouseDown){ //鼠標按下了,開始移動 var left = currentTh.offset().left; var paddingBorderLen = currentTh.outerWidth()-currentTh.width(); currentTh.width((e.pageX-left-paddingBorderLen)+'px'); } } }, mouseup:function (e) { isMouseDown = false; currentTh = null; $('table th').css('cursor','auto'); $('#mask').remove(); } }); });
本插件可能要修改的地方
1.遮罩層的id,mask可能和你的某些元素沖突,建議換成其它的
2.遮罩層的z-index可能不夠大,當你拖動停不下來的時候,把z-index提高,最大值為2147483647