如何使用Javascript滚动到下一个div? [英] How to scroll to next div using Javascript?

查看:68
本文介绍了如何使用Javascript滚动到下一个div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我正在创建一个网站,里面有很多占据100%身高的Div。
我想制作一个按钮,这样点击它就可以顺利滚动到下一个div。
我已经编码了一些内容,所以当点击它时,它会滚动到特定的div。

So I'm making a website with a lot of Divs that take 100% height. And I want to make a button so when it's clicked to smoothly scroll to next div. I've coded something so when its clicked, it scrolls to specific div.

$(".next").click(function() {
    $('html,body').animate({
        scrollTop: $(".p2").offset().top},
        'slow');
});

body{
  margin: 0;
  height: 100%;
}

.p1{
  height: 100vh;
  width: 70%;
  background-color: #2196F3;
}
.p2{
  height: 100vh;
  width: 70%;
  background-color: #E91E63;
}
.p3{
  height: 100vh;
  width: 70%;
  background-color: #01579B;
}

.admin{
  background-color: #B71C1C;
  height: 100vh;
  position: fixed;
  right: 0%;
  top: 0%;
  width: 30%;
  float: left;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="p1">
  
</div>
<div class="p2">
  
</div>
<div class="p3">
  
</div>

<div class="admin">
  
  <button class="next">NEXT</button>
  
</div>

推荐答案

要完成这项工作,您需要确定当前显示的 div 。为此,您可以将类应用于当前显示的元素。然后你可以使用 next()来遍历它们。

To make this work you need to identify the currently displayed div. For that you can apply a class to the element which is currently shown. Then you can use next() to traverse through them all.

另请注意,在下面的示例中,在所有元素上添加了一个公共类, .p ,以便干掉CSS并使DOM遍历更容易。

Also note in the below example the addition of a common class on all elements, .p, in order to DRY up the CSS and make DOM traversal easier.

$(".next").click(function() {
  var $target = $('.p.active').next('.p');
  if ($target.length == 0)
    $target = $('.p:first');
    
  $('html, body').animate({
    scrollTop: $target.offset().top
  }, 'slow');

  $('.active').removeClass('active');
  $target.addClass('active');
});

body {
  margin: 0;
  height: 100%;
}

.p {
  height: 100vh;
  width: 70%;
}
.p1 {
  background-color: #2196F3;
}
.p2 {
  background-color: #E91E63;
}
.p3 {
  background-color: #01579B;
}

.admin {
  background-color: #B71C1C;
  height: 100vh;
  position: fixed;
  right: 0%;
  top: 0%;
  width: 30%;
  float: left;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="p p1 active"></div>
<div class="p p2"></div>
<div class="p p3"></div>
<div class="admin">
  <button class="next">NEXT</button>
</div>

这篇关于如何使用Javascript滚动到下一个div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆