may*_*ank 24 html javascript hash
我需要使用滚动页面anchor tag.
现在我正在做:
<a href="#div1">Link1</a>
<div id='div1'>link1 points me!!</div>
Run Code Online (Sandbox Code Playgroud)
当我点击Link1时,这个工作正常,页面滚动到id为"div1"的div.
关键是,我不想更改我#div点击后作为后缀的URL Link1.
我尝试使用锚点href作为
void(0);
Run Code Online (Sandbox Code Playgroud)
和
location.hash='#div1';
return false;
e.preventdefault;
Run Code Online (Sandbox Code Playgroud)
如何避免更改URL?
hen*_*ser 41
使用jQuery的animate从Jeff Hines那里得到这个答案:
function goToByScroll(id){
$('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}
Run Code Online (Sandbox Code Playgroud)
如果您正在使用jQuery,请不要忘记将库添加到您的项目中.
编辑:此外,请确保您仍然"返回false;" 在链接的点击处理程序中,否则它仍然会将"#div1"添加到您的URL(感谢@niaccurshi)
sta*_*One 27
scrollIntoView 所有其他方法都失败了,做得最好!
document.getElementById('top').scrollIntoView(true);
Run Code Online (Sandbox Code Playgroud)
哪里'top'是你想去的HTML标签的ID.
让您的生活更轻松,尝试以下内容,让我知道是否还有其他事情;-)
<div>top</div>
<div style="height: 800px;"> </div>
<div><a href="javascript:void(0);" onclick="window.scroll(0,1);">click here</a></div>
Run Code Online (Sandbox Code Playgroud)
仅供参考:你只需要玩一条/一条线href="javascript:void(0);" onclick="window.scroll(0,1);"就可以了.
祝你有美好的一天!
仅在文档准备好时将此代码添加到 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;
}
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
41804 次 |
| 最近记录: |