如何让这段代码只能平滑滚动我想要的元素?

时间:2015-09-03 14:17:23

标签: javascript jquery html css

我有一个流畅的滚动代码,效果很好,问题是它运行得很好。我有其他元素使用"#"是标签(例如:但我不希望标签被平滑滚动作为目标。我有以下平滑的滚动代码:

    jQuery(document).ready(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;
   }
 }
});
});

无论如何都要将其修改为仅定位页面的锚点而非标签锚点

1 个答案:

答案 0 :(得分:0)

如果您不想影响#作为href值的链接,您应该使用的语法如下所示:

$("[attribute!='value']")

因此,在您的情况下,您将href指定为属性,将#指定为值。

$("a[href!='#']").on('click', function(e){
    e.preventDefault();
    //do stuff
});