Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

jquery - How to scroll to next div using Javascript?

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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...