javascript 用js动态改变td宽度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3653174/
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
dynamical change td width with js
提问by kristina
I need to change the width of a td using javascript. The value of the width will be pulled in and then I need to multiple it to get a percentage. I just need to know how to write the js so far I have got to here but it is not working
我需要使用 javascript 更改 td 的宽度。宽度的值将被拉入,然后我需要乘以它以获得一个百分比。我只需要知道如何编写 js 到目前为止我已经到了这里但它不起作用
<script language="JavaScript">
var divWidth = 66*0.4;
document.write("<td width="+divWidth+">");
document.getElementById("myRow").write("<td width="+divWidth+">");
</script>
<table>
<tr>
<td id="myRow"></td>
</tr>
回答by scunliffe
I think you want this:
我想你想要这个:
<script type="text/javascript">
var divWidth = 66*0.4;
document.getElementById("myRow").setAttribute('width', divWidth);//defaults to pixels
//or if you really want this as a percentage
document.getElementById("myRow").setAttribute('width', divWidth+'%');//percent
</script>
<table>
<tr>
<td id="myRow"></td>
</tr>
</table>
However, there are some things I would adjust in your code. I changed the language attribute in the script tag (now deprecated) to a type="javascript". The idon your TD element is myRowI would change this to something reflecting the cellvs. the row.
但是,我会在您的代码中调整一些内容。我将脚本标签(现已弃用)中的语言属性更改为type="javascript". 将id您的TD元素是myRow我反映了这个变化的东西电池主场迎战排。
回答by Anri?tte Myburgh
Try using jQuery, it's a Javascript library/framework and what you're trying to do above will be ten times easier using jQuery.
尝试使用jQuery,它是一个 Javascript 库/框架,你在上面尝试做的事情使用jQuery会容易十倍。
With jQuery, your code will be:
使用 jQuery,您的代码将是:
$(document).ready(function () {
var newWidth = $("#myRow").width();
$("#myRow").width(newWidth*0.4);
}
//edit:
//编辑:
Sorry, I had the multiple wrong.
对不起,我错了多个。

