在使用 JQuery 加载时滚动到新页面上的片段标识符?

发布于 2024-10-20 05:41:28 字数 577 浏览 9 评论 0原文

我试图看看是否可以有一些简单的 HTML 标记,如下所示:

<a href="www.mysite.com/pageXXX#location1"></a>
<a href="www.mysite.com/page1#location1"></a>
<a href="www.mysite.com/page2#location1"></a>
<a href="www.mysite.com/page3#location1"></a>

...然后,当 new 时,让它向下滚动到 ID #location1页面加载某种简单的 JQuery 脚本?或者,如果这可以通过scrollTo插件来实现,我该如何解决呢?

问题是该链接存在于 pageXXX 上,并且要滚动到的 ID 位于所有页面上,即。 pageXXX、page1、page2、page3 等......理想情况下,如果还有一种方法可以从 URL 中删除井号标记和标识符,那就太好了,但目前我所追求的只是让它顺利地向下滚动到新页面上的 ID。

I'm trying to see if its possible to have some simple HTML markup like so:

<a href="www.mysite.com/pageXXX#location1"></a>
<a href="www.mysite.com/page1#location1"></a>
<a href="www.mysite.com/page2#location1"></a>
<a href="www.mysite.com/page3#location1"></a>

...and then, have it scroll down to the ID #location1 when the new page loads with a simple JQuery script of some sort? Or if this is something that could be achieved with the scrollTo plugin, how might I go about that instead?

The catch is that the link exists on pageXXX, and the ID to be scrolled to is on ALL pages, ie. pageXXX, page1, page2, page3, etc......Ideally, if there's also a way to remove the hash mark and the identifier from the URL that would be great too, but at the moment just having it smoothly scroll down to the ID on the new page is all I'm after.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

ゞ花落谁相伴 2024-10-27 05:41:28

您可以添加一个 setTimeout 以便它等待一会儿然后向下滚动?

function goToByScroll(id){
        $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}
var hash = window.location.hash;

setTimeout(function(){
      goToByScroll(hash);
},2000);

You could add a setTimeout so it waits a bit then scrolls down?

function goToByScroll(id){
        $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}
var hash = window.location.hash;

setTimeout(function(){
      goToByScroll(hash);
},2000);
悲喜皆因你 2024-10-27 05:41:28

另一种选择:

而不是

<a href="www.mysite.com/pageXXX#location1"></a>

尝试

<a href="www.mysite.com/pageXXX?location1"></a>

您可以通过这种方式获取要放入链接中的哈希值,

var nothash = window.location.search;
var hash = nothash.substring(1);

:参考: https://developer.mozilla.org/en/DOM/window.location

在这里,您可以防止页面在任何地方跳转,并且您可以执行后续步骤(将哈希值放入动画滚动函数中),而不必担心,如果它射得足够快。

An alternative:

Instead of

<a href="www.mysite.com/pageXXX#location1"></a>

Try

<a href="www.mysite.com/pageXXX?location1"></a>

You can get the hash to put into the link this way:

var nothash = window.location.search;
var hash = nothash.substring(1);

Reference: https://developer.mozilla.org/en/DOM/window.location

Here you prevent the page from jumbing anywhere and you can do the next steps (putting the hash in a animated scroll function) without worrying about, if it fires fast enough.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文