如何从 Javascript 代码设置单元格宽度(HTML 表格)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15329719/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to set the cell width (HTML table) from Javascript code
提问by user1460819
I have an HTML table. How can I change the width of one of the cells of that table from Javascript code? For example, I have a button, and when I press it, I want the width of one particular column to be changed. How can I do this?
我有一个 HTML 表格。如何从 Javascript 代码更改该表中一个单元格的宽度?例如,我有一个按钮,当我按下它时,我希望更改某一特定列的宽度。我怎样才能做到这一点?
回答by ktm5124
You could do it without jQuery.
你可以在没有 jQuery 的情况下做到这一点。
Working example: http://jsfiddle.net/qFDBk/1/
工作示例:http: //jsfiddle.net/qFDBk/1/
var btn = document.getElementById('btn');
btn.onclick = function() {
var tbl = document.getElementById('tbl');
var td = tbl.rows[0].cells[0];
td.width = '500px';
td.style.backgroundColor = 'blue';
}
回答by isherwood
Here's how you might do it with jQuery, a popular JavaScript library:
以下是使用流行的 JavaScript 库 jQuery 实现的方法:
$('td:nth-child(2)').css('width', '100px');
回答by Ravi Gadag
Use CSS method to apply the width.
使用 CSS 方法应用宽度。
$('td').css('width','200px');
explanation :
解释 :
- Get All td Elements. and Apply the CSS property width and set it's value to 200px. for every td element.
$('td')
is the tagSelector. it will select all td elements.- .css() will apply the style rules which u mentioned.
- 获取所有 td 元素。并应用 CSS 属性宽度并将其值设置为 200px。对于每个 td 元素。
$('td')
是标签选择器。它将选择所有 td 元素。- .css() 将应用您提到的样式规则。