我在my web site上使用以下Javascript来创建平滑的滚动效果,当用户单击“联系我们”链接时,滚动到页脚中的联系人信息。我从CSS-Tricks post on smooth scrolling上的Devin Sturgeon的评论中得到了这段代码片段。我唯一的猜测是,问题产生于锚链接不在设定位置,而是在固定菜单中。据该帖子称,该片段应该只需剪切并粘贴即可。
<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 :(得分:1)
此行$('a[href*=#]:not([href=#])')
返回一个空集,因此您的点击处理程序未在任何dom元素上设置。浏览器使用旧时尚锚标记<a name="contact"> </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;
}
}
});
});