jQuery Smooth Scroll 跨浏览器问题
我有一小段代码可以产生平滑的滚动来锚定标签并再次返回。我的网站设计有一个高度为 170px 的固定标题。因此,为了弥补这一点,java 已进行如下修改。
var jump=function(e)
{
e.preventDefault();
var target = $(this).attr("href");
$('html,body').animate(
{
scrollTop: $(target).offset().top-170 // modification
},1000,function()
{
location.hash = target;
});
}
$(document).ready(function()
{
$('a[href*=#]').bind("click", jump);
return false;
});
此代码在 Chrome 和 Safari 中完美运行,但在 IE 和 Safari 中运行良好。 Firefox 会滚动到预期位置并向下跳转 170 像素。
有什么想法吗?
谢谢, 担
I have a small snippet of code to produce a smooth scroll to anchor tags and back again. My site design has a fixed header of height 170px. So to compensate for this the java has been modified as below.
var jump=function(e)
{
e.preventDefault();
var target = $(this).attr("href");
$('html,body').animate(
{
scrollTop: $(target).offset().top-170 // modification
},1000,function()
{
location.hash = target;
});
}
$(document).ready(function()
{
$('a[href*=#]').bind("click", jump);
return false;
});
This code works perfectly in Chrome and Safari, but in IE & Firefox it scrolls to the intended location and jumps 170px further down the page.
Any ideas?
Thanks,
Dan
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是,当你的动画完成时,你设置了
location.hash
这使得浏览器跳转到锚点。作为一个简单的解决方法,不要阻止单击时的哈希更改,而是保存当前滚动位置。这样你的浏览器就会立即跳转到哈希值。要为整个事情设置动画,您可以捕获
hashchange
事件,并立即跳回您上次停下的位置,并将过渡动画设置为您想要的内容。较旧的浏览器可能会遇到一些闪烁,看看它是否适合您,值得一试。
或者,您也可以按照自己的方式进行操作,只需在标记中添加锚点的实际 ID 前缀,以防止浏览器自动跳转到那里,然后将前缀添加到单击的哈希中,以使用选择器定位元素。
另请参阅 @fudgey's 答案以清理
'html,body'
选择器。The problem is that when your animation finishes, you set
location.hash
which makes the browser jump to the anchor. As a simple workaround, don't prevent the hash change on the click, save the current scroll position instead. That way your browser would jump to the hash straight away.To animate the whole thing, you can catch the
hashchange
event, and immediately jump back where you've left off and animate the transition to your heart's content.Older browsers might experience some flicker, see if it's accaptable for you, worth a try.
Alternatively you can do it your way, just prefix the actual IDs of your anchors in the markup to prevent the browser automatically jumping there, then add the prefix to the clicked hash to locate the element with a selector.
Also see @fudgey's answer for cleaning up your
'html,body'
selector.我看到有两个问题:
$('html,body')
进行滚动。 Opera 似乎将两者视为单独的元素,因此您会看到页面滚动两次。这是一个很好的跨浏览器修复。There are two problems I see:
$('html,body')
for scrolling. Opera seems to treat both as separate elements, so you will see the page scroll twice. Here is a nice cross-browser fix.