【问题标题】:show and hide divs using setInterval in jquery在 jquery 中使用 setInterval 显示和隐藏 div
【发布时间】:2014-06-06 07:12:31
【问题描述】:

在下面的代码中,我需要的是,如果用户单击“开始”按钮,“div1”必须显示 5 秒,5 秒后“div1”必须隐藏,“div2”必须显示。我为此使用了一个 jquery 函数,但我认为必须对此进行修改。任何人都可以在我缺乏的地方帮助我。

<!DOCTYPE HTML>
<html>
    <head>
        <meta charset="utf-8">
        <title>Untitled Document</title>
    </head>

    <body>

    <input type='button' value="go"/>

    <div id='div1' style='width:100px; height:100px; background:green; display:none;' >
        <h1>Loader</h1>
    </div>
    <div id='div2' style='width:100px; height:100px; background:#F00; display:none;'></div> 

    <script>
        $('html').addClass('js');

        $(function() {

            var timer = setInterval( 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++; 

            }

        });
    </script>

    </body>
</html>

【问题讨论】:

  • 你必须在你的脚本之前调用jQuery library文件
  • 对不起,我忘了在问题中添加 jquery ......但我要问的是我需要在用于我要问的场景的函数中修改什么......我是对 jquery 来说非常新。

标签: jquery


【解决方案1】:
  <!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>

<input type='button' value="go" id="go"/>

<div id='div1' style='width:100px; height:100px; background:#000; display:none;' >

</div>
<div id='div2' style='width:100px; height:100px; background:#ccc; display:none;'></div> 
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script>

$(function() {
    $('#go').click(function(){
        showDiv1();
    });
});
function showDiv1(){
    $('#div1').show();
    setTimeout(function(){ $('#div1').hide(); showDiv2() },3000);
    }
function showDiv2(){
    $('#div2').show();
    setTimeout(function(){ $('#div2').hide(); showDiv1() },3000);
}


</script>

</body>
</html>

试试这个

【讨论】:

  • “div2”不需要任何超时。一旦显示出来它就会像那样出现......我需要在上面的代码中进行更改。
  • 稍作修改...上面的脚本运行良好...这是最终脚本...
【解决方案2】:

你可以这样做:

function animateDivs(id) {
    var divId = (id == "div1") ? "div2": "div1";    
    $("#" + id)
        .fadeIn(300).delay(5000)
        .fadeOut(300, function() {
            animateDivs(divId);
         });
}

$("#go").click(function() {
    animateDivs("div1");
});

jsFiddle Demo

【讨论】:

    猜你喜欢
    • 2011-11-06
    • 2013-06-18
    • 1970-01-01
    • 1970-01-01
    • 2018-01-04
    • 2011-08-20
    • 1970-01-01
    • 2012-02-01
    相关资源
    最近更新 更多