使用 URL 中没有 # 的锚点滚动 [英] Scroll with anchor without # in URL

查看:33
本文介绍了使用 URL 中没有 # 的锚点滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 anchor tag 滚动页面.

I need to scroll through a page using anchor tag.

现在我正在做:

<a href="#div1">Link1</a>

<div id='div1'>link1 points me!!</div>

当我点击 Link1 时,这工作正常,页面滚动到 ID 为div1"的 div.
关键是,我不想更改以 #div 作为后缀的 URL,一旦我点击了 Link1.

This works fine when I clicked on Link1, the page scrolls to the div with id "div1".
The point is, I do not want to change my URL which takes #div as suffix once I clicked on Link1.

我尝试将锚点 href 设为

I tried with anchor href as

void(0);

location.hash='#div1';
return false;

e.preventdefault;

如何避免更改网址?

推荐答案

使用 jQuery 的动画从 Jeff Hines 那里得到这个答案:

Take this answer from Jeff Hines using jQuery's animate:

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

如果您使用 jQuery,请不要忘记将库添加到您的项目中.

If you're using jQuery don't forget to add the library to your project.

另外,请确保您仍然返回假;"在链接的点击处理程序中,否则它仍会将#div1"添加到您的 URL(感谢 @niaccurshi)

Also, make sure that you still "return false;" in the click handler for the link, otherwise it'll still add the "#div1" to your URL (thanks @niaccurshi)

这篇关于使用 URL 中没有 # 的锚点滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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