自动滚动到每个div暂停,然后连续进行

时间:2019-06-24 16:58:23

标签: javascript jquery html

我想创建一个函数,以“ class = res-”暂停滚动到每个div,然后移至下一个div暂停,依此类推-一旦到达最后一个div,它将在顶部重新启动并连续执行此功能。任何帮助将不胜感激!

<!--*class "res-<some number>" is dynamic so it will never have a static "some number"-->
<div class="main_window">
  <div class="res-1">
    scroll to me then pause for 5 seconds next move to res-2
  </div>

  <div class="res-2">
    scroll to me then pause for 5 seconds next move to res-8-5
  </div>

  <div class="res-8-5">
    scroll to me then pause for 5 seconds next move to top and repeat 
  </div>
</div>

2 个答案:

答案 0 :(得分:2)

您也可以通过jQuery来实现。

$(document).ready(function() {
    var selector = "div[class^='res-']";
    var firstSelect = $("div[class^='res-']:first");
    var lastSelect = $("div[class^='res-']:last");

    $(firstSelect).addClass('active');

    setInterval(function() {
        var next = $(".main_window .active") .removeClass('active').next(selector);

        if (!next.length) next = next.prevObject.siblings(':first');
    
        next.addClass('active');

        $section = $('.active');

        scroll();
    }, 5000);

});

function scroll() {
    $('html, body').animate({ scrollTop: ($section.offset().top)},300);    
}
div[class^='res-'] {
    height: 100vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main_window">
    <div class="res-1">scroll to me then pause for 5 seconds next move to res-2
    </div>
    <div class="res-2">scroll to me then pause for 5 seconds next move to res-8-5
    </div>
    <div class="res-8-5">scroll to me then pause for 5 seconds next move to top and repeat
    </div>
</div>

您可以在此处检查其输出-https://jsfiddle.net/ydeepak1/jord3spu/11/

答案 1 :(得分:1)

您可以使用JavaScript setInterval()element.scrollIntoView()来实现。

请注意 .scrollIntoView() doesn't have too good cross-browser support.

的选项

还要注意,这将尝试相对于窗口而不是其父窗口滚动元素。

const elements = document.querySelectorAll('[class^=res-]');
let active = 0;
setInterval(()=>{
  if( ++active >= elements.length) active = 0;
  
  //poor support for options
  elements[active].scrollIntoView({
    behavior:'smooth',
    block:'start' //Where to align current item: 'start', 'end' or 'center'
  })
},5000)
[class^=res-]{
  /* huge margin to see scrolling effect*/
  margin-bottom:500px;
}
<div class="main_window">
  <div class="res-1">
    scroll to me then pause for 5 seconds next move to res-2
  </div>

  <div class="res-2">
    scroll to me then pause for 5 seconds next move to res-8-5
  </div>

  <div class="res-8-5">
    scroll to me then pause for 5 seconds next move to top and repeat 
  </div>
</div>