我需要使用anchor tag
滚动页面。
现在我正在做的是:
<a href="#div1">Link1</a>
<div id='div1'>link1 points me!!</div>
当我点击Link1时,页面会滚动到id为"div1“的div。
重点是,我不想改变我的网址,它以#div
作为后缀,一旦我点击Link1
。
我尝试使用锚点href作为
void(0);
和
location.hash='#div1';
return false;
e.preventdefault;
如何避免更改URL?
发布于 2013-03-05 19:50:57
使用jQuery的animate从Jeff Hines那里获取答案:
function goToByScroll(id){
$('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}
如果您正在使用jQuery,不要忘记将该库添加到您的项目中。
编辑:另外,确保你仍然在链接的点击处理程序中"return false;“,否则它仍然会在你的URL中添加"#div1”(谢谢@niaccurshi)
发布于 2016-05-17 22:49:52
当所有其他方法都失败时,scrollIntoView
做得最好!
document.getElementById('top').scrollIntoView(true);
其中'top'
是您要转到的html标记的id。
发布于 2014-11-25 22:46:56
仅在文档就绪时将此代码添加到jquery中
参考:http://css-tricks.com/snippets/jquery/smooth-scrolling/
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^/ / , '') == this.pathname.replace(/^/ / , '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
https://stackoverflow.com/questions/15223006
复制相似问题