jQuery:调用 URL 时滚动到锚点,替换浏览器行为 [英] jQuery: Scroll to anchor when calling URL, replace browsers behaviour

查看:22
本文介绍了jQuery:调用 URL 时滚动到锚点,替换浏览器行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经知道了 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,而是创建一个像 _foo 这样的 id 的锚点代码>(类似于 ).您可以处理 $(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆