自动滚动到每个Div暂停,然后连续移动



我想创建函数以滚动到每个div,class = res-"暂停,然后移动到下一个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>

您也可以通过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/

您可以使用JavaScript setInterval()element.scrollIntoView()

请注意, .scrollIntoView()的选项没有很好的跨浏览器支持。

还请注意,这将尝试相对于窗口而不是其父。

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>

最新更新