【www.gdgbn.com--jquery】

表格拖动调整列宽jquery代码
为了能在所有需要该效果的页面使用,并且不需要更改页面任何html,我把所有的代码整合在  $(document).ready(function() {});  中,并写入一个独立的js文件。
用一个1像素宽的div来模拟一条竖线,在页面载入后添加到body元素中

$(document).ready(function() {
     $("body").append(" ");
 });

接下来是鼠标移动到表格纵向边框上鼠标变型的问题,起初我考虑在表头中添加一个很小的块级元素触发mousemove 和mouseo教程ut事件,但为了简单起见,我还是选择为整个表头添加该事件。

  在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);
        });
    }
});

本文来源:http://www.gdgbn.com/wangyezhizuo/28907/