鍍金池/ 問答/HTML/ table 列寬度左右拉伸

table 列寬度左右拉伸

這是我在網(wǎng)上看到的一段代碼

    var tTD; //用來存儲(chǔ)當(dāng)前更改寬度的Table Cell,避免快速移動(dòng)鼠標(biāo)的問題
    var table = document.getElementById(val);
    for (let j = 0; j < 2; j++) {
      console.log(table.rows[0].cells[j], 'jjjjj');
      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寬度
        //table = tTD; while (table.tagName != ‘TABLE') table = table.parentElement;
        //tTD.tableWidth = table.offsetWidth;
      };
      table.rows[0].cells[j].onmouseup = function () {
        //結(jié)束寬度調(diào)整
        if (tTD == undefined) tTD = this;
        tTD.mouseDown = false;
        tTD.style.cursor = 'default';
      };
      table.rows[0].cells[j].onmousemove = function () {
        //更改鼠標(biāo)樣式
        if (event.offsetX > this.offsetWidth - 10)
          this.style.cursor = 'col-resize';
        else
          this.style.cursor = 'default';
        //取出暫存的Table Cell
        if (tTD == undefined) tTD = this;
        //調(diào)整寬度
        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);
          //調(diào)整列寬
          tTD.style.width = tTD.width;
          tTD.style.cursor = 'col-resize';
          //調(diào)整該列中的每個(gè)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;
          }
          //調(diào)整整個(gè)表
          //table.width = tTD.tableWidth + (tTD.offsetWidth – tTD.oldWidth);
          //table.style.width = table.width;
        }
      };
    }
    
    但是只適用于單行表頭
    

clipboard.png
如果是這種的該如何修改使用。

回答
編輯回答
別傷我

cell中的內(nèi)容做成寬度自適應(yīng)的。外部cell的寬度變了,瀏覽器會(huì)重繪,里面的元素也會(huì)重繪。內(nèi)部元素的寬度設(shè)定為百分比,讓其可自動(dòng)伸縮。

2018年7月10日 16:23