jquery 如何滚动到上一个具有相同类的div

n3schb8v  于 2023-06-22  发布在  jQuery
关注(0)|答案(1)|浏览(103)

我有一个相当长的页面,里面有很多类元素。还有两个按钮:nextprev
This script滚动到下一个元素对我来说很好:

$('.button').click(function() {
   var target;
   $("p").each(function(i, element) {
     target = $(element).offset().top;
     if (target - 10 > $(document).scrollTop()) {
       return false; // break
     }
   });
   $("html, body").animate({
     scrollTop: target
   }, 700);
});

有人能帮我解决prev问题吗?

bvhaajcl

bvhaajcl1#

这应该是工作:

$(document).ready(function(){
    $('.button.next').click(function() {
       var target;
       $("p").each(function(i, element) {
         target = $(element).offset().top;
         if (target - 10 > $(document).scrollTop()) {
           return false; // break
         }
       });
       $("html, body").animate({
         scrollTop: target
       }, 700);
    });
    
    $('.button.prev').click(function() {
       var target;
       $("p").each(function(i, element) {
         current = $(element).offset().top;
         if (current + 10 > $(document).scrollTop()) {
           if (i == 0){
             target = 0;
           }
           else {
             target = $("p").eq(i-1).offset().top
           }
           return false; // break
         }
       });
       $("html, body").animate({
         scrollTop: target
       }, 700);
    });
});
p {
  height:600px;
}
.button {
  position:fixed;
  cursor:pointer;
  top:5%; 
} 
.next {
  right:5%;
}
.prev {
  right:15%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="button prev">PREV</div>
<div class="button next">NEXT</div>

<h1>Welcome to My Homepage</h1>

<p>This is the first paragraph.</p>
<p>This is the second paragraph.</p>
<p>This is the third paragraph.</p>
<p>This is the last paragraph.</p>

相关问题