因此,我使用以下脚本来平滑滚动命名 anchor ,但当目标位于页面中 anchor 上方时,它不起作用(不会向上滚动)。
$(document).ready(function(){
$('a[href^="#"]:not(.top)').click(function(event){
event.preventDefault();
var full_url = this.href;
var parts = full_url.split("#");
var trgt = parts[1];
var target_offset = $("#"+trgt).offset();
var target_top = target_offset.top;
$('html, body').animate({scrollTop:target_top}, 500);
});
});
有人知道如何让它变得友好吗?
编辑:
我目前正在使用它向上滚动,但如果您知道在一个函数中执行此操作的更简洁的方法,请发布:
$('.top').click(function(event){
event.preventDefault();
$('html, body').animate({scrollTop:0}, 500);
});
最佳答案
它对我有用,使用元素 ID 而不是命名 anchor 。
无论如何,您应该使用 ID 而不是命名 anchor - HTML5 中不推荐使用命名 anchor 。即:
<a name="section1"><h1>Section One</h1></a>
should be:
<h1 id="section1">Section One</h1>
您可以将滚动合并到一个函数中:
$('a[href^="#"]').live('click',function(event){
event.preventDefault();
var target_offset = $(this.hash).offset() ? $(this.hash).offset().top : 0;
$('html, body').animate({scrollTop:target_offset}, 500);
});
关于Jquery 向上滚动 anchor ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7037713/