JS实现表格列宽拖动javascript

/ / 2017-08-30   阅读:2499
1 效果 可以用纯JS就可以实现,如下,是正常情况下的表格: 拖动表格标题中间线,拖动后效果如下: 2 代码 HTML代码: <!DOCTYPE html> <html> <head>    <title>...
1 效果
可以用纯JS就可以实现,如下,是正常情况下的表格:

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


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

我要评论

昵称:
验证码:

最新评论

共0条 共0页 10条/页 首页 上一页 下一页 尾页
意见反馈