2013-07-08 28 views
0

我在my web site上使用以下Javascript来创建平滑滚动效果,当用户单击联系我们链接时,滚动到页脚中的联系人信息。我从Devin Sturgeon对CSS-Tricks post on smooth scrolling的评论中得到了这段代码片段。我唯一的猜测是,问题是由于锚链接不在固定位置,而是在固定菜单中。据后,该段应通过剪切和粘贴在它只是工作。无法从固定菜单项目顺利滚动到工作

<script type="text/javascript"> 
    $('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; 
      } 
     } 
    }); 
</script> 
+0

请发布您的菜单和目标项目的HTML。它们对于它是否会起作用至关重要。为了完整起见,请确保在执行此代码之前将jQuery加载到您的页面**,并且此代码在** 的所有HTML元素之后**。 – FakeRainBrigand

+0

@FakeRainBrigand它将代码移过所有html元素并将其添加到ready事件后工作。感谢您的输入! –

+0

把它放在身体的尽头是很好的,因为浏览器是从上到下的。如果您的代码位于底部,则会在HTMl已经解析并显示后加载它,这可以让用户不会长时间盯着白色屏幕。这通常是一个好习惯。 – FakeRainBrigand

回答

1

所以您单击处理程序不被任何DOM元素上设置这一行$('a[href*=#]:not([href=#])')将返回一个空集。浏览器正在使用旧时尚定位标记<a name="contact">&nbsp;</a>进行滚动。

@FakeRainBrigand是正确的,当您添加您的点击处理程序时,您的文档未被完全加载。只需将其添加到准备好的事件。

$(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 - 181 
        }, 1000); 
        return false; 
       } 
      } 
     }); 

}); 
+0

照顾它。谢谢! –