最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set timer on body onload? - Stack Overflow

programmeradmin1浏览0评论

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>

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>
Share Improve this question edited Feb 12, 2014 at 9:06 Suhaib Janjua 3,57216 gold badges69 silver badges87 bronze badges asked Feb 12, 2014 at 7:17 JazzJazz 532 gold badges3 silver badges10 bronze badges 2
  • 3 please explain a bit more. – Konza Commented Feb 12, 2014 at 7:21
  • @Konza - The time which i set on onload function that time interval I want to display my div. – Jazz Commented Feb 12, 2014 at 7:38
Add a ment  | 

3 Answers 3

Reset to default 1
  • 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/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>

Try this:

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

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

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

Use jquery, it less..

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

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

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

 </body>
发布评论

评论列表(0)

  1. 暂无评论