jQuery:调用URL时滚动至锚点,替换浏览器行为 [英] jQuery: Scroll to anchor when calling URL, replace browsers behaviour
问题描述
我已经知道jQuery插件ScrollTo,但到目前为止我还没有找到实现以下目标的方法:
I already know the jQuery plugin ScrollTo, but I didn't find any way up to now to realize the following:
用户访问我的网站(通过键入,而不是通过单击页面上的链接来访问)domain.com/bla.php#foo
The users gets to my site (by typing, NOT by clicking a link on my page) domain.com/bla.php#foo
和锚点"#foo"存在.现在,我希望用户的浏览器不会自动滚动到"#foo",而是希望平滑滚动,以使元素"#foo"位于视图的中间,而不是位于视图的绝对顶部.用户查看.
and the anchor "#foo" exists. Now I want that the browser of the user does NOT automatically scroll to "#foo", instead I want to smoothly scroll so that the element '#foo' is about in the middle of the view and NOT on the absolute top position of the users view.
到目前为止谢谢!
推荐答案
如果您没有创建实际的锚点foo
,而是创建一个具有ID的锚点,例如_foo
(类似于<a id="_foo">
).您可以通过$(document).ready
来实现.
If you don't create the actual anchor foo
, but rather create your anchor with an id like _foo
(something like <a id="_foo">
). You can handle the $(document).ready
to achieve this.
类似(伪代码)的
$(document).ready(function() {
var elem = $('#_' + window.location.hash.replace('#', ''));
if(elem) {
$.scrollTo(elem.left, elem.top);
}
});
这篇关于jQuery:调用URL时滚动至锚点,替换浏览器行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!