[英]document.getElementById('box').style.width=“10px”; Doesn't work?
I cannot seem to get this script to work. 我似乎无法让这个脚本工作。 Can anyone please help? 有人可以帮忙吗? The DIV's width is not defined. DIV的宽度未定义。 It just stretches across the whole page. 它只是延伸到整个页面。
<html>
<head>
<style type="text/css">
#box{
height:100px;
border:3px;
border-style:solid;
border-color:#000;
}
</style>
<script>
document.getElementById('box').style.width="10px";
</script>
</head>
<body>
<div id="box"></div>
Your script is running before the <div>
is rendered on the page. 在页面上呈现<div>
之前,您的脚本正在运行。 Try it like this: 试试这样:
<html>
<head>
<style type="text/css">
#box{
height:100px;
border:3px;
border-style:solid;
border-color:#000;
}
</style>
</head>
<body>
<div id="box"></div>
<script type="text/javascript">
document.getElementById('box').style.width="10px";
</script>
</body>
</html>
And don't forget to close your <body>
and <html>
tags. 并且不要忘记关闭<body>
和<html>
标签。
To prove that it is, look at this example. 为证明这一点,请看这个例子。 I moved the script back to the <head>
section and changed the width setting to run when the window is finished loading. 我将脚本移回<head>
部分并将宽度设置更改为在窗口加载完成后运行。
<html>
<head>
<style type="text/css">
#box{
height:100px;
border:3px;
border-style:solid;
border-color:#000;
}
</style>
<script type="text/javascript">
alert('test');
window.onload = function() {
document.getElementById('box').style.width="10px";
}
</script>
</head>
<body>
<div id="box"></div>
</body>
</html>
You'll see the 'test' alert message before the box is rendered. 在呈现框之前,您将看到“测试”警报消息。
The element does not exist on the page yet. 该元素尚未存在于页面上。 JavaScript can not access/manipulate an element until it has been loaded in the DOM. 在将元素加载到DOM中之前,JavaScript无法访问/操作元素。 You can overcome this by moving you <script>
block to above the closing </body>
. 你可以通过将<script>
块移动到结束</body>
。 Or use an window.load event. 或者使用window.load事件。
An example of the former using your code is here - http://jsfiddle.net/ycWxH/ 前一个使用您的代码的例子在这里 - http://jsfiddle.net/ycWxH/
if you will use jquery it is more easy to do that. 如果你将使用jquery,那么更容易做到这一点。 that is if you will only use jquery framework here is the code 也就是说,如果你只在这里使用jquery框架就是代码
$('#box').height(10);
just a reminder, window.onload
is fired when page fully loaded. 只是提醒一下,当页面完全加载时会触发window.onload
。 refer to http://www.javascriptkit.com/dhtmltutors/domready.shtml 请参阅http://www.javascriptkit.com/dhtmltutors/domready.shtml
<script>
function doMyStuff() = {};
if ( document.addEventListener ) {
document.addEventListener( "DOMContentLoaded", doMyStuff, false );
} else if ( document ) {
document.attachEvent("onreadystatechange",function(){
if ( document.readyState === "complete" ) {doMyStuff();}
});}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.