So I am using the following script to scroll named anchors smoothly, but it doesn't work when the destination is above the anchor in the page (won't scroll upwards).
$(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 开发者_Go百科target_top = target_offset.top;
$('html, body').animate({scrollTop:target_top}, 500);
});
});
Does anyone know how to make it up friendly?
Edit:
I am currently using this to scroll upwards now, but if you know of a cleaner way to do it in one function please post away:
$('.top').click(function(event){
event.preventDefault();
$('html, body').animate({scrollTop:0}, 500);
});
It works for me, using element IDs instead of named anchors.
You should be using IDs instead of named anchors anyway - named anchors are deprecated in HTML5. That is:
<a name="section1"><h1>Section One</h1></a>
should be:
<h1 id="section1">Section One</h1>
And you can combine the scrolling in one function:
$('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);
});
精彩评论