当页面加载时,如果锚点在URL中,如何防止页面“跳转”?

时间:2022-05-28 01:23:08

How to prevent with jQuery default browser behavior, jump to anchor if anchor is in the link when page loads?

如何使用jQuery默认浏览器行为,在页面加载时跳转到锚点?

var myLink = document.location.toString();

if (myLink.match('#')) {
 $('html, body').animate({ scrollTop: 0 }, 0); // OR
 $(window).scrollTop();
}

Or.... can't find solution... searched... and searched

或....找不到解决方案…搜索…和搜索

3 个解决方案

#1


4  

use return false / event.preventDefault on your links

使用return false / event。preventDefault在你的链接

var myLink = document.location.toString();

if (myLink.match('#')) {
    $('html, body').animate({ scrollTop: 0 }, 0); // OR
    $(window).scrollTop();
    return false;
}

Or do you mean that you want o smooth scroll to the position of the ID you are refering to in your hash sign?

或者你的意思是你想要平滑滚动到你在你的哈希符号中所指的ID的位置?

after reading your comments ignore this message.

在阅读你的评论之后,忽略这条信息。

maybe like this: http://jsbin.com/ajafor/4#hello

也许是这样的:http://jsbin.com/ajafor/4你好

#2


1  

<a href="#" class="link">link Text</a>
$(function()
{
    $('a.link').attr('href','javascript:void(0);')
});

or add manually

或添加手动

<a href="javascript:void(0);" class="link">link Text</a>

#3


0  

I did this by including localScroll and scrollTo, then simply call:

我做了这个,包括localScroll和scrollTo,然后简单地调用:

$(function () { $.localScroll(); });

#1


4  

use return false / event.preventDefault on your links

使用return false / event。preventDefault在你的链接

var myLink = document.location.toString();

if (myLink.match('#')) {
    $('html, body').animate({ scrollTop: 0 }, 0); // OR
    $(window).scrollTop();
    return false;
}

Or do you mean that you want o smooth scroll to the position of the ID you are refering to in your hash sign?

或者你的意思是你想要平滑滚动到你在你的哈希符号中所指的ID的位置?

after reading your comments ignore this message.

在阅读你的评论之后,忽略这条信息。

maybe like this: http://jsbin.com/ajafor/4#hello

也许是这样的:http://jsbin.com/ajafor/4你好

#2


1  

<a href="#" class="link">link Text</a>
$(function()
{
    $('a.link').attr('href','javascript:void(0);')
});

or add manually

或添加手动

<a href="javascript:void(0);" class="link">link Text</a>

#3


0  

I did this by including localScroll and scrollTo, then simply call:

我做了这个,包括localScroll和scrollTo,然后简单地调用:

$(function () { $.localScroll(); });