您好,欢迎访问一九零五行业门户网

JQuery表格拖动调整列宽效果(自己动手写的)_jquery

类似于桌面程序中的表格拖动表头的效果,当鼠标停留在表头边框线上时,鼠标会变成表示左右拖动的形状,接着拖动鼠标,会在表格中出现一条随鼠标移动的竖线,最后放开鼠标,表格列宽会被调整。最近比较空闲,便自己动手尝试实现,在此分享下小小的成果。
首先需要如图所示的鼠标图标文件,在自己的硬盘中搜索*.cur,肯定能找到。
为了能在所有需要该效果的页面使用,并且不需要更改页面任何html,我把所有的代码整合在 $(document).ready(function() {}); 中,并写入一个独立的js文件。
用一个1像素宽的div来模拟一条竖线,在页面载入后添加到body元素中
$(document).ready(function() {$(body).append(
);});
接下来是鼠标移动到表格纵向边框上鼠标变型的问题,起初我考虑在表头中添加一个很小的块级元素触发mousemove 和mouseout事件,但为了简单起见,我还是选择为整个表头添加该事件。
在th的mousemove事件中处理鼠标变型:
$(th).bind(mousemove, function(event) {var th = $(this);//不给第一列和最后一列添加效果if (th.prevall().length <= 1 || th.nextall().length < 1) {return;}var left = th.offset().left;//距离表头边框线左右4像素才触发效果if (event.clientx - left < 4 || (th.width() - (event.clientx - left)) < 4) {th.css({ 'cursor': '/web/page/frameset/images/splith.cur' });//修改为你的鼠标图标路径}else {th.css({ 'cursor': 'default' });}});
当鼠标按下时,显示竖线,并设置它的高度,位置css属性,同时记录当前要改变列宽的th对象,因为一条边框线由两个th共享,这里总是取前一个th对象。
$(th).bind(mousedown, function(event) {var th = $(this);//与mousemove函数中同样的判断if (th.prevall().length < 1 | th.nextall().length < 1) {return;}var pos = th.offset();if (event.clientx - pos.left < 4 || (th.width() - (event.clientx - pos.left)) < 4) {var height = th.parent().parent().height();var top = pos.top;$(#line).css({ height: height, top: top,left:event .clientx,display: });//全局变量,代表当前是否处于调整列宽状态linemove = true;//总是取前一个th对象if (event.clientx - pos.left < th.width() / 2) {currth = th.prev();}else {currth = th;}}});
接下来是鼠标移动时,竖线随之移动的效果,因为需要当鼠标离开th元素也要能有该效果,该效果写在body元素的mousemove函数中
$(body).bind(mousemove, function(event) {if (linemove == true) {$(#line).css({ left: event.clientx }).show();}});
最后是鼠标弹起时,最后的调整列宽效果。这里我给body 和th两个元素添加了同样的mouseup代码。我原先以为我只需要给body添加mouseup函数,但不明白为什么鼠标在th中时,事件没有触发,我只好给th元素也添加了代码。水平有限,下面完全重复的代码不知道怎么抽出来。
$(body).bind(mouseup, function(event) {if (linemove == true) {$(#line).hide();linemove = false;var pos = currth.offset();var index = currth.prevall().length;currth.width(event.clientx - pos.left);currth.parent().parent().find(tr).each(function() {$(this).children().eq(index).width(event.clientx - pos.left);});}});$(th).bind(mouseup, function(event) {if (linemove == true) {$(#line).hide();linemove = false;var pos = currth.offset();var index = currth.prevall().length;currth.width(event.clientx - pos.left);currth.parent().parent().find(tr).each(function() {$(this).children().eq(index).width(event.clientx - pos.left);});}});
好了,只要在需要这个效果的页面中引入包含以上代码的js文件,就可以为页面中表格添加该效果。
另外以上代码在火狐中自定义鼠标图标的代码没出效果,所用的jquery为1.2.6
效果文件下载
其它类似信息

推荐信息