【问题标题】:Why isn't my function running on document load as expected?为什么我的函数没有按预期在文档加载时运行?
【发布时间】:2012-08-03 22:04:10
【问题描述】:

此代码应设置元素高度;但是没有添加任何样式。我错过了什么明显的东西吗?

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>

感谢您的帮助!

【问题讨论】:

  • 一个非常简单的解决方案是将您的脚本放在&lt;/body&gt; 标记之前。然后你可以做setGround()

标签: javascript html height


【解决方案1】:

你应该使用

window.onLoad = setGround; 

而不是

document.onload = setGround;

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      你可以用这个:

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

      但是如果你想看到变化,你应该使用这个在section标签上创建边框:

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

      【讨论】:

        【解决方案4】:

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

        http://jsfiddle.net/mowglisanu/r6NzE/

        【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-09-11
        • 2010-09-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多