在网址中使用不带#的锚来滚动 [英] Scroll with anchor without # in URL

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

问题描述

我需要使用锚标记滚动页面。



现在我正在做:

 < a href = #DIV1 >链接1< / A> 

< div id ='div1'> link1指向我!!< / div>

这个工作正常,当我点击Link1时,页面会滚动到ID为div1的div。

问题是,当我点击 Link1 时,我不想更改以 #div 作为后缀的URL。 / code>。



我试着用anchor href作为

 空隙(0); 

 的location.hash = '#DIV1'; 
返回false;

e.preventdefault;

如何避免更改网址?

解决方案

使用jQuery的动画从Jeff Hines中得到这个答案:
$ b

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

$ / code>

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

编辑:另外,请确保您仍然返回false。在链接的点击处理程序中,否则它仍会将#div1添加到您的网址(谢谢@niaccurshi)


I need to scroll through a page using anchor tag.

Right now I'm doing:

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

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

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.

I tried with anchor href as

void(0);

and

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

e.preventdefault;

How to avoid changing the URL?

解决方案

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

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

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

Edit: 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)

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

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