Javascript 动态更改 div 宽度百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8254299/
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
Change div width in percentage dynamically
提问by Jim
I have a div
我有一个div
<div id="chart" style="position:relative; width: 100%; float:left; height: 220px;">
</div>
And I need to change width dynamically. I found solution like:
而且我需要动态更改宽度。我找到了类似的解决方案:
var elem = document.getElementById('chart');
elem.style.width = 70 + "%";
But that not work's. Where I do wrong ? Thanks in advance...
但那不行。我哪里做错了?提前致谢...
回答by Niels
Try this fiddle: http://jsfiddle.net/TrrCh/
试试这个小提琴:http: //jsfiddle.net/TrrCh/
I think you are trying to run the Javascript before the HTML is loaded. Bind it to the document.ready and it should be working
我认为您正在尝试在加载 HTML 之前运行 Javascript。将它绑定到 document.ready 并且它应该可以工作
window.onload=function(){
var elem = document.getElementById('chart');
elem.style.width = 70 + "%";
}
回答by Selvakumar Ponnusamy
It works well for me.
这对我来说很有用。
Browsers Used: IE8 and FF3.
使用的浏览器:IE8 和 FF3。
Could you verify once other wise you may try this
你能不能验证一下,否则你可以试试这个
elem.style.width = "70%";
This is the code I tested
这是我测试的代码
<body>
<div id="chart" style="position:relative; width: 100%; float:left; height: 220px;border:2px Solid #FF0000">
</div>
</body>
var elem = document.getElementById('chart');
elem.style.width = 70+ "%";