JQuery拖动表头边框线调整表格列宽效果代码

2020-05-23 06:10:48易采站长站整理


$("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

效果文件下载

————————————————————————更新——————————————

关于拖动时会选中内容的BUG,将以下一行代码添加到$(document).ready函数里就行了


$("body").bind("selectstart", function() { return !lineMove; });