简体   繁体   English

jQuery-如何使按钮滚动到下一个div,但如果向上滚动则响应

[英]JQuery - How to make a button scroll to next div, but respond if scrolled up

So my dilemma is this: 所以我的困境是:

I want a button on my website that is fixed to the screen and after being clicked will scroll you to the next element in the body. 我希望网站上的按钮固定在屏幕上,单击后将您滚动到正文中的下一个元素。 BUT I also want it to know if you have scrolled up and update whichever is the next element accordingly. 但是我也想让它知道您是否向上滚动并相应地更新下一个元素。 For example, if you have clicked the button twice you are on the 3rd paragraph, but if you scroll back up to the second and click the button again, it should take you to the 2nd paragraph again. 例如,如果您单击了两次按钮,则您位于第三段,但是如果您向上滚动到第二段并再次单击该按钮,则应该再次进入第二段。

How can I accomplish this? 我该怎么做?

Heres the type of function I'm looking at for scrolling the view 这是我正在寻找的用于滚动视图的函数类型

$(document).ready(function(){
    var attr = $("p").first();
    $('.button').click(function() {
       attr=attr.next();
       $("html, body").animate({
         scrollTop: $(attr).offset().top
    }, 700);
    });
});

HTML: HTML:

<div class="button">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>

Here's a plunker example: http://plnkr.co/edit/5nNcroXUXespRw1P8jZt?p=info 这是一个小例子: http ://plnkr.co/edit/5nNcroXUXespRw1P8jZt?p=info

How can I make this change as you scroll up? 当您向上滚动时,我该如何进行更改?

Find all p elements and scroll to the one that has an offset greater than the current scroll position ie $(document).scrollTop() 找到所有p元素,然后滚动到偏移量大于当前滚动位置的元素,即$(document).scrollTop()

Here's an example forked from yours. 这是的一个例子

Something like this... I added some arbitrary : +30, as it doesn't work with +1, for the first element :=) 像这样...我为第一个元素添加了任意值:+30,因为它不适用于+1:=)

<script>
$(document).ready(function(){
    var pos  = $("p").first().position();

    $('.button').click(function() {
      attr =    $(document.elementFromPoint(pos.left, pos.top+30));
       attr=attr.next();
       $("html, body").animate({
         scrollTop: $(attr).offset().top
    }, 700);
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM