简体   繁体   English

我怎么能用 jquery 做滚动?

[英]How can ı do scrolltop with jquery?

<div class="logo-contentBlock"> 
   <a href="#logo-first-content" class="content-page-scroll-1">BLOG</a>
</div>
<div class="logo-contentBlock"> 
   <a href="#logo-second-content" class="content-page-scroll-2">BLOG</a>
</div>
   .
   .
   .
  <div id="#logo-first-content">.....</div>
  <div id="#logo-second-content">....</div>




$(".content-page-scroll-1").click(function() {
    $('html, body').animate({
        scrollTop: $('#content-first-content').offset().top - 60
    },5000);
});
$(".content-page-scroll-2").click(function() {
    $('html, body').animate({
        scrollTop: $('#content-second-content').offset().top - 60
    }, 5000);
});
$(".content-page-scroll-3").click(function() {
    $('html, body').animate({
        scrollTop: $('#logo-thirt-content').offset().top - 60
    }, 5000);
});

Hello, ı just want scrolltop 60 but ı have 9 content like that that means a lot of jquery.你好,我只想要scrolltop 60,但我有9个这样的内容,这意味着很多jquery。 How can i do shorten my code with jquery?如何使用 jquery 缩短我的代码?

The thing to notice here is that the only thing changing between the callbacks is the CSS-selector.这里要注意的是,回调之间唯一改变的是 CSS 选择器。 To stay DRY here, I would define a function that takes a CSS-selector and returns the click-handler.为了保持干燥,我将定义一个 function,它采用 CSS 选择器并返回点击处理程序。

Working off your example, for example like so:处理您的示例,例如:

const cbFactory = selector => () => {
    $('html, body').animate({
        scrollTop: $(selector).offset().top - 60
    },5000);
};

$(".content-page-scroll-1").click(cbFactory('#content-first-content'));
$(".content-page-scroll-2").click(cbFactory('#content-second-content'));
$(".content-page-scroll-3").click(cbFactory('#logo-thirt-content'));

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

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