所以我使用以下脚本顺利滚动命名锚点,但当目标位于页面中的锚点上方时(不向上滚动),它不起作用。
$(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);
});
答案 0 :(得分:3)
它适用于我,使用元素ID而不是命名锚点。
您应该使用ID而不是命名锚点 - 在HTML5中不推荐使用命名锚点。那就是:
<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);
});