简体   繁体   English

定时循环将div滑入和滑出

[英]Slide div in and out on timed loop

I need some help please. 我需要一些帮助。 I trying to get my div "hello" to slide in and out on a timed loop. 我试图让我的div“ hello”在定时循环中滑入和滑出。 Like the following below. 如下所示。

  • Slide IN (pause) for: 5 seconds 向内滑动(暂停)5秒
  • Slide OUT (pause) for: 12 seconds 滑出(暂停)12秒
  • Slide IN (pause) for: 5 seconds 向内滑动(暂停)5秒
  • Slide OUT (pause) for: 12 seconds 滑出(暂停)12秒
  • Just keep on doing that! 只要继续这样做!

    Here's an example on JSFiddle https://jsfiddle.net/08nr9ya5/ 这是JSFiddle上的示例https://jsfiddle.net/08nr9ya5/

    <div id="hello">
      Hello World!
    </div>
    
    function show() {
      setTimeout(function() {
        $('#hello')
          .css('margin-right', -$(this).width())
          .animate({
            marginLeft: -1500
          }, 900);
      }, 2000);
      hide();
    }
    
    function hide() {
      setTimeout(function() {
        $('#hello')
          .css('margin-right', -$(this).width())
          .animate({
            marginLeft: 0
          }, 900);
      }, 5000);
    }
    
    show();
    

    Actually I missed that you called hide() from the show() function without a timeout. 实际上,我想念您没有超时就从show()函数调用hide()的情况。 And your timeouts were around the code to change the div, not for starting the next function. 而且您的超时是围绕更改div的代码进行的,而不是为了启动下一个函数。

    I've cleaned it up a bit, you don't need 3 timeouts, only two. 我已经整理了一下,您不需要3次超时,只需两次。 I also swapped around the code in the functions - the show function now actually has the code in it to make the div slide in, and the hide function to slide it out. 我还交换了函数中的代码-show函数现在实际上包含使div滑入的代码,以及hide函数将其滑出的代码。 Before you had the opposite, just wrapped in timeouts... 在遇到相反的情况之前,只需将超时包裹起来...

    function show() {
       // slide in immediatly when show() is called
       $('#hello')
            .css('margin-right', -$(this).width())
            .animate({
              marginLeft: 0
        }, 900);
        // calls hide() after 5 seconds
        setTimeOut(function(){
            hide();
        }, 5000);
    }
    
    function hide() {
        // slide out immediatly when hide() is called
        $('#hello')
          .css('margin-right', -$(this).width())
          .animate({
            marginLeft: -1500
          }, 900);
        // calls show() after 12 seconds
        setTimeout(function(){
            show();
        }, 12000);
    }
    
    hide();
    

    https://jsfiddle.net/08nr9ya5/2/ https://jsfiddle.net/08nr9ya5/2/

    声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

     
    粤ICP备18138465号  © 2020-2024 STACKOOM.COM