【问题标题】:How can I change height of a Table element with JavaScript?如何使用 JavaScript 更改 Table 元素的高度?
【发布时间】:2021-05-06 00:16:15
【问题描述】:

我可以更改bgcolorwidth,但不能更改height。有什么问题?

function change() {
  document.getElementById('tabelID').bgColor = 'green';
  document.getElementById('tabelID').height = 50;
  document.getElementById('tabelID').width = 100;
}
<button onclick='change();'>change now</button>
<table id='tabelID' bgcolor='red' height='20' width='20'></table>

【问题讨论】:

  • 您应该使用 CSS 而不是过时的表格属性。

标签: javascript html css dom height


【解决方案1】:

属性和属性并不总是具有相同的名称。

height 属性对应于clientHeight 属性,但这是一个只读属性。使用setAttribute()更改属性。

但正如我在评论中提到的,使用 CSS 比使用过时的属性更好。

function change() {
  document.getElementById('tabelID').bgColor = 'green';
  document.getElementById('tabelID').setAttribute("height", 50);
  document.getElementById('tabelID').setAttribute("width", 100);
}
<button onclick='change();'>change now</button>
<table id='tabelID' bgcolor='red' height='20' width='20'></table>

【讨论】:

    【解决方案2】:

    table 上的 bgcolorwidthheight 属性已被弃用。您应该改用 CSS 属性 background-colorwidthheight。这是一个通过切换 CSS 类来更改表格的更新示例:

    function toggleChanges() {
        document.getElementById('tabelID').classList.toggle('larger');
    }
    .mytable {
        background-color: red;
        width: 50px;
        height: 50px;
    }
    
    .mytable.larger {
        background-color: green;
        width: 100px;
        height: 100px;
    }
    <button onclick='toggleChanges();'>toggle changes</button>
    <table id='tabelID' class='mytable'></table>

    【讨论】:

    • 感谢大家的快速回答。他们都工作得很好。太好了!
    • @StefanHesman 如果我的回答解决了您的问题,请考虑接受(通过单击答案分数下方的灰色复选标记),谢谢!
    【解决方案3】:

    我会让你运行这段代码,你需要使用 css,并为高度和宽度定义一个度量(px、%、...),也许这可以帮助你!

    <!DOCTYPE html>
    <html>
    <head>
    </head>
    <body>
    
    <button onclick='change();'>change now</button>
    <table style="background-color:red ;height:20px ;width:20px;" id='tabelID' ></table>
    
    <script type='text/javascript'>
    function change() {
       document.getElementById('tabelID').style.backgroundColor = 'green';
       document.getElementById('tabelID').style.height = "50px";
       document.getElementById('tabelID').style.width = "100px";
    }
    </script>
    </body>
    </html>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-07-04
      • 1970-01-01
      • 1970-01-01
      • 2019-01-19
      • 1970-01-01
      • 2015-05-06
      • 2015-05-19
      相关资源
      最近更新 更多