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

javascript - Show and hide divs at a specific time interval using jQuery but stop the last div - Stack Overflow

programmeradmin3浏览0评论

I need code to automatically hide div1 and show div2 after a specific amount of time, say 10sec or 15sec.
I read this post : Show and hide divs at a specific time interval using jQuery,

but it repeats every 10 seconds. I just need to hide div1 and show div2 once.

I need code to automatically hide div1 and show div2 after a specific amount of time, say 10sec or 15sec.
I read this post : Show and hide divs at a specific time interval using jQuery,

but it repeats every 10 seconds. I just need to hide div1 and show div2 once.

Share Improve this question edited Jan 6, 2020 at 17:06 SherylHohman 18k18 gold badges93 silver badges96 bronze badges asked Nov 29, 2012 at 4:07 lala90lala90 1511 gold badge3 silver badges11 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 6

Assuming that your divs have the ids "div1" and "div2", and that "div1" starts out visible and "div2" starts out hidden, then you can hide the first and show the second after x milliseconds like this:

$("#div1").delay(10000).hide(0, function() {
    $("#div2").show();
});

You can use .fadeOut() and .fadeIn() or other animation methods instead of .hide() and .show() if you like.

Put the above code inside a document ready handler if the intention is for this to happen automatically, or in a click handler or whatever if it is in response to something the user does.

Demo: http://jsfiddle/s7NXz/

If you have more than two divs and you want to cycle through them exactly once you can do something like this:

var $divs = $("div").hide(),    // use an appropriate selector here
    current = 0;

$divs.eq(0).show();             // show the first

function showNext() {
    if (current < $divs.length - 1) { // if not past the end then
        $divs.eq(current).delay(2000).fadeOut('fast', function() {
            current++;
            $divs.eq(current).fadeIn('fast');
            showNext();
        });
    }
}
showNext();

Demo: http://jsfiddle/s7NXz/1/

First div1 is visible and div2 is hidden. To show div2 and hide div1 after a specific time, you can add a mon class, x:

 $('.x').delay(1000).toggle();

You can adjust delay and toggle speed. Toggle will display matching hidden elements and hide matching shown elements.
See jQuery toggle docs

$('html').addClass('js');

$(function() {

  var timer = setTimeout( showDiv, 5000);

  var counter = 0;

  function showDiv() {
    if (counter ==0) { counter++; return; }

    $('div','#container')
      .stop()
      .hide()
      .filter( function() { return this.id.match('div' + counter); })   
      .show('fast');
    counter == 3? counter = 0 : counter++; 

  }

});

use setTimeout in place of setInterval

$("button").click(function(){
  $("p").hide(1000);
  alert("The paragraph is now hidden");
});
发布评论

评论列表(0)

  1. 暂无评论