1. 程式人生 > >原生js實現table列寬的滑鼠拖動事件

原生js實現table列寬的滑鼠拖動事件

var tTD; //用來儲存當前更改寬度的Table Cell,避免快速移動滑鼠的問題
var table = document.getElementById("tableId");    //table的id名稱
for (j = 0; j < table.rows[0].cells.length; j++) {
    table.rows[0].cells[j].onmousedown = function () {
        //記錄單元格
        tTD = this;
        if (event.offsetX > tTD.offsetWidth - 10) {
            tTD.mouseDown = true;
            tTD.oldX = event.x;
            tTD.oldWidth = tTD.offsetWidth;
        }
    };
    table.rows[0].cells[j].onmouseup = function () {
        //結束寬度調整
        if (tTD == undefined) tTD = this;
        tTD.mouseDown = false;
        tTD.style.cursor = 'default';
    };
    table.rows[0].cells[j].onmousemove = function () {
        //更改滑鼠樣式
        if (event.offsetX > this.offsetWidth - 10)
            this.style.cursor = 'col-resize';
        else
            this.style.cursor = 'default';
        //取出暫存的Table Cell
        if (tTD == undefined) tTD = this;
        //調整寬度
        if (tTD.mouseDown != null && tTD.mouseDown == true) {
            tTD.style.cursor = 'default';
            if (tTD.oldWidth + (event.x - tTD.oldX) > 0)
                tTD.width = tTD.oldWidth + (event.x - tTD.oldX);
            //調整列寬
            tTD.style.width = tTD.width;
            tTD.style.cursor = 'col-resize';
            //調整該列中的每個Cell
            table = tTD;
            while (table.tagName != 'TABLE') table = table.parentElement;
            for (j = 0; j < table.rows.length; j++) {
                table.rows[j].cells[tTD.cellIndex].width = tTD.width;
            }
        }
    };
}