简体   繁体   English

如何对多个元素使用相同的jQuery滚动功能

[英]How to use the same jQuery scrolling function for multiple elements

I have a scrolling function that reveals a 'scroll to top' element when user scrolls to 160 pixels, when clicked this element the page scrolls to the top of the page. 我有一个滚动功能,当用户滚动到160像素时,它会显示“滚动到顶部”元素,单击此元素时,页面将滚动到页面顶部。

I want to use that function create more scroll buttons which will be revealed at different stages in the document and that scroll to different areas. 我想使用该功能创建更多的滚动按钮,这些按钮将在文档的不同阶段显示出来,并滚动到不同的区域。

For example when the user scrolls to 400 pixels down the element "next" appears when clicking it page scrolls 300px down, they get to 900px from top a new scroll element appears which when clicked scrolls down to 1300px, and so on. 例如,当用户向下滚动到400像素时,单击该元素时“ next”会向下滚动300px,然后从顶部滚动至900px,就会出现一个新的滚动元素,单击该元素会向下滚动至1300px,依此类推。

here is the jQuery code i have: 这是我拥有的jQuery代码:

   $(document).ready(function(){

$(window).scroll(function(){
    if ($(this).scrollTop() > 160)  {
        $('.scrollToTop').fadeIn();
    } else {
        $('.scrollToTop').fadeOut();
    }

});

$('.scrollToTop').click(function(){
    $('html, body').animate({scrollTop : 0},800);
    return false;
});
});

HTML: HTML:

<div class="scrollToTop-container">
<a href="#" class="scrollToTop"><img src="img/icon_arrow_up.png" width="24" height="24" />      <br/>Scroll to top</a>
</div>

i hope thats not too confusing. 我希望那不是太令人困惑。

Thanks 谢谢

Maybe you can use a function like this I made reusing some parts of your code: 也许您可以使用这样的函数,我重用了部分代码:

function scroll(id,show,limit,timeout){
  $(window).scroll(function(){
    if ($(this).scrollTop() > show)  {
      $(id).fadeIn();
    } else {
      $(id).fadeOut();
    }
 });
 $(id).click(function(){
   $('html, body').animate({scrollTop : limit},timeout);
   return false;
 });
}

And then use it like this: 然后像这样使用它:

scroll(".scrollToTop",160,0,800);

where first parameter is class or id you want to be affected, second is the position of the element at certain height (from top), third is limit (where you want to scroll up) and last one is the duration of the animate function. 第一个参数是您要受影响的类或ID,第二个参数是元素在特定高度处的位置(从顶部开始),第三个参数是限制(您要向上滚动的位置),最后一个是animate功能的持续时间。


EDIT: You may also like to stop on specific px, not only scroll to top, so I changed the function to set the scrollTop position at your desire. 编辑:您可能还想停止在特定的px上,不仅滚动到顶部,所以我更改了功能,以根据需要设置scrollTop位置。

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

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