javascript 如何在身体加载上设置计时器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21721159/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 21:33:23  来源:igfitidea点击:

How to set timer on body onload?

javascripthtml

提问by Jazz

I want to set timer on body onload eventHandlerto call function where I show hide div.

我想在身体上设置计时器onload eventHandler来调用我显示隐藏 div 的函数。

<body onload="">
    <div style="display:none;"> hide </div>
</body>

回答by UweB

  • For better readability, I've put the code in a separate function.
  • I've added an id to the divfor easier selection through javascript.
  • In the onloadattribute, I'm calling setInterval, which gets an anonymous function as a first parameter.
  • This function will be called every time after the interval (1000 ms) elapses.
  • The function will then select the element with the id theDiv, and set its css displayattribute to block, or none(depending on the previous value).
  • 为了更好的可读性,我将代码放在一个单独的函数中。
  • 我已经添加了一个 id 以便div通过 javascript 更容易地选择。
  • onload属性中,我调用setInterval了一个匿名函数作为第一个参数。
  • 每次间隔(1000 毫秒)过去后都会调用此函数。
  • 然后该函数将选择具有 id 的元素theDiv,并将其 cssdisplay属性设置为block, 或none(取决于先前的值)。

JSFiddle for demonstration: http://jsfiddle.net/GAE8L/1/

用于演示的 JSFiddle:http: //jsfiddle.net/GAE8L/1/

Note that the first parameter for setIntervalis just the function name, not a function call (so no parenthesis!):

请注意,for的第一个参数setInterval只是函数名,而不是函数调用(所以没有括号!):

<body onload="setInterval(onTimerElapsed, 1000);">
    <div id="theDiv" style="display:none;">
        hide
    </div>
</body>

<script type="text/javascript">
    function onTimerElapsed() {
        var myDiv = document.getElementById('theDiv');
        myDiv.style.display = myDiv.style.display === 'none' ? 'block' : 'none';
    }
</script>

回答by Jokey

Try this:

试试这个:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>

<div id="div1" style="display:none;">
hide
</div>

<script>
$(function() {
    setTimeout(function() {
            $('#div1').show();
    }, 1000);
});
</script>

回答by user3044272

Use jquery, it less..

使用jquery,它更少..

  function foo() {
    // method show should be called.
    $("#idDiv").show();
  }

  function bar() {
    setTimeout(foo(), 1000)
  }

</script>
</code>
 <body onload="bar()">

 </body>