为什么不是'我的函数未按预期在文档加载时运行

Why isn't my function running on document load as expected?

本文关键字:文档 加载 运行 函数 我的 为什么不      更新时间:2023-09-26

此代码应设置元素高度;但是没有添加任何样式。我是不是错过了一些显而易见的东西?

function setGround() { 
    document.getElementById('content').style.height = '40px';
} 
document.onload = setGround; 

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>

谢谢你的帮助!

不要使用document.onload,而是使用window.onload

请参阅http://jsfiddle.net/mowglisanu/r6NzE/

您可以使用这个:

function setGround() { 
    document.getElementById('content').style.height = '40px';
} 
document.onload = setGround;

但是,如果你想看到变化,你应该使用以下方法在部分标签上创建边界:

<section id="content" style='border:1px solid fuchsia;' >
<p>sf </p>
</section>     

您应该使用

window.onLoad = setGround; 

而不是

document.onload = setGround;

您将javascript代码放在哪里了?它在detect-css.js中吗?

这项工作:

<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>