如何在body onload上设置定时器? [英] How to set timer on body onload?

查看:174
本文介绍了如何在body onload上设置定时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

 < body onload => 
< div style =display:none;>隐藏< / div>
< / body>


解决方案 为了提高可读性,我已经将代码放在一个单独的函数中。
  • 我已经为 div 添加了一个id,以便通过javascript更轻松地进行选择。

  • onload 属性中,我调用 setInterval ,一个匿名函数作为第一个参数。
  • 这个函数在间隔(1000 ms)后每次都会被调用。

  • 选择id为 theDiv 的元素,并将其css display 属性设置为 block none (取决于前一个值)。


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



    请注意, setInterval 的第一个参数仅仅是函数名称,而不是函数调用(因此没有括号!): p>

     < body onload =setInterval(onTimerElapsed,1000);> 
    < div id =theDivstyle =display:none;>
    隐藏
    < / div>
    < / body>

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


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

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

    解决方案

    • For better readability, I've put the code in a separate function.
    • I've added an id to the div for easier selection through javascript.
    • In the onload attribute, 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 display attribute to block, or none (depending on the previous value).

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

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

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

    这篇关于如何在body onload上设置定时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆