原生js实现 table表格列宽拖拽

原生js实现 table表格列宽拖拽

代码如下:

	function resizeTableCol(id){
            var i,
                self,
                table = document.querySelector(id),
                header = table.rows[0],
                tableX = header.clientWidth,
                length = header.cells.length;

            for (i = 0; i < length; i++) {
                header.cells[i].onmousedown = function () {
                    self = this;
                    if (event.offsetX > self.offsetWidth - 10) {
                        self.mouseDown = true;
                        self.oldX = event.x;
                        self.oldWidth = self.offsetWidth;
                    }
                };
                header.cells[i].onmousemove = function () {
                    if (event.offsetX > this.offsetWidth - 10) {
                        this.style.cursor = 'col-resize';
                    } else {
                        this.style.cursor = 'default';
                    }
                    if (self == undefined) {
                        self = this;
                    }
                    if (self.mouseDown != null && self.mouseDown == true) {
                        self.style.cursor = 'default';
                        if (self.oldWidth + (event.x - self.oldX) > 0) {
                            self.width = self.oldWidth + (event.x - self.oldX);
                        }
                        self.style.width = self.width;
                        table.style.width = tableX + (event.x - self.oldX) + 'px';
                        self.style.cursor = 'col-resize';
                    }
                };
                table.onmouseup = function () {
                    if (self == undefined) {
                        self = this;
                    }
                    self.mouseDown = false;
                    self.style.cursor = 'default';
                    tableX = header.clientWidth;
                };
            }
        }
		//使用时传入table的id名
		setTimout(resizeTableCol('#table'),300);

效果如下:
在这里插入图片描述
在这里插入图片描述

相关推荐
©️2020 CSDN 皮肤主题: 像素格子 设计师:CSDN官方博客 返回首页