蒙国造博客

JS实现表格列宽拖动

在数据表格中,有时候需要拖动表格宽度,查看完整的数据,是很常用的功能。

1 效果

可以用纯JS就可以实现,如下,是正常情况下的表格:

拖动表格标题中间线,拖动后效果如下:

查看DEMO

2 代码

HTML代码:

<!DOCTYPE html>
<html>
<head>
   <title>演示</title>
   <script type="text/javascript" src="tabSize.js"></script>
   <script type="text/javascript">
      window.onload = function() {
         tabSize.init('resizeTable');
      };
   </script>
   <style>
      .resizeBox{overflow-x: auto; width: 500px;}
      table{width: 100%;border: 1px solid #000;border-collapse:collapse;}
      th{background: #ccc;}
      th, td{border: 1px solid #000;}
   </style>
</head>
<body>
   <div class="resizeBox">
      <table id="resizeTable">
         <thead>
            <tr><th>标题1</th><th>标题2</th><th>标题3</th></tr>
         </thead>
         <tbody>
            <tr><td>第1行</td><td>第1行</td><td>第1行</td></tr>
            <tr><td>第2行</td><td>第2行</td><td>第1行</td></tr>
            <tr><td>第3行</td><td>第3行</td><td>第1行</td></tr>
         </tbody>
      </table>
   </div>
</body>
</html>

JS代码:

"use strict";
var tabSize = tabSize || {};
tabSize.init = function (id) {
    var i,
        self,
        table = document.getElementById(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;
        };
    }
};

点击下载完整代码

退出移动版