这个jQuery是正确的吗?

时间:2015-04-19 11:26:16

标签: jquery scroll smooth

我想在我的页面上有流畅的滚动效果。并且iv找到了这段代码

jQuery(function($) {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});

这没关系,但是没有使用我的“go top”链接。所以我用教程检查其他页面并执行此操作:

jQuery(function($) {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
  $('a.go-top').click(function() {
    $('html, body').animate({scrollTop:0}, 'slow');
    return false;
  });
});

现在一切正常。但是我不知道jQuery,你能告诉我这个代码是否正确,或者你可以,我应该在这里改变什么?谢谢!

1 个答案:

答案 0 :(得分:1)

它不适用于您的go top链接,因为您只查找具有要点击的ID属性的链接:$('a[href*=#]:not([href=#])')。您的go-top是一个非ID的类,如果您要将其更改为ID,则不需要添加的代码。