Javascript 为什么我的函数没有按预期在文档加载时运行?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11836675/
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
Why isn't my function running on document load as expected?
提问by cmplieger
This code should set an elements height; however no style gets added. Am I missing something obvious?
此代码应设置元素高度;但是没有添加样式。我错过了一些明显的东西吗?
function setGround() {
document.getElementById('content').style.height = '40px';
}
document.onload = setGround;
The HTML is quite basic:
HTML 非常基础:
<!DOCTYPE html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Template</title>
<link rel="stylesheet" type="text/css" href="css/default.css"/>
<link rel="stylesheet" type="text/css" href="css/orange.css"/>
<script type="text/javascript" src="javascript/detect-css.js"></script>
</head>
<body>
<header>
<div id="logo"></div>
</header>
<section id="sidebar"><p>sf </p>
</section>
<section id="content"><p>sf </p>
</section>
</body>
</html>
Thank you for your help!
感谢您的帮助!
采纳答案by Musa
Don't use document.onload
use window.onload
instead.
不要使用document.onload
usewindow.onload
代替。
回答by MKT
you can use this:
你可以使用这个:
function setGround() {
document.getElementById('content').style.height = '40px';
}
document.onload = setGround;
but if you want see changes, you should create border on section tag by use this:
但是如果你想看到变化,你应该使用这个在部分标签上创建边框:
<section id="content" style='border:1px solid fuchsia;' >
<p>sf </p>
</section>
回答by IshaniNet
You should use
你应该使用
window.onLoad = setGround;
instead of
代替
document.onload = setGround;
回答by user1560066
Where have you placed the javascript-code? Is it in the detect-css.js?
你把javascript代码放在哪里了?它在detect-css.js 中吗?
This works:
这有效:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Template</title>
<link rel="stylesheet" type="text/css" href="css/default.css"/>
<link rel="stylesheet" type="text/css" href="css/orange.css"/>
<script language="javascript">
function resize(){
document.getElementById("content").style.height='100px';
}
</script>
</head>
<body onload="resize()">
<header><div id="logo"></div></header>
<section id="sidebar"><p>sf </p>
</section>
<section id="content" style="background-color:#CCC; display:block;"><p>sf </p>
</section>
</body>
</html>