【问题标题】:How to scroll to previous div with same class如何滚动到具有相同类的上一个 div
【发布时间】:2016-01-10 13:23:25
【问题描述】:

我的页面很长,里面有很多类元素。还有 2 个按钮: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 吗?

【问题讨论】:

  • 你能把代码贴在这里吗?

标签: jquery button next


【解决方案1】:

这应该可行:

$(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>

【讨论】:

  • 我的为什么不像提供的示例那样左右滚动? jsfiddle.net/k66gLuLk/3 我在页面加载时对 div 进行排序。谢谢
猜你喜欢
  • 1970-01-01
  • 2012-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-24
相关资源
最近更新 更多