UPDATE: Exactly like this: but in jQuery... Maybe I should just spend sometime porting it. http://davidwalsh.name/mootools-onload-smoothscroll
The context: Wordpress site, with subnav navigation set to /page/#idname to scroll down the page.
I'm having a hard time trying to figure out how to make the page scroll to the ID (with offset) and setting location without jumping. And if you load the page with the hash, how would I get the page to scroll down from the top?
//SMOOTH SCROLL
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}
var locationPath = filterPath(location.pathname);
var scrollElem = scrollableElement('html', 'body');
$('a[href*=#]').each(function() {
var thisPath = filterPath(this.pathname) || locationPath;
if ( locationPath == thisPath
&& (location.hostname == this.hostname || !this.hostname)
&& this.hash.replace(/#/,'') ) {
var $target = $(this.hash), target = this.hash;
if (target) {
var targetOffset = $target.position().top - 60;
$(this).click(function(event) {
event.preventDefault();
$(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
location.hash = target+"-section"
});
});
}
}
});
// use the first element that is "scrollable"
function scrollableElement(els) {
for (var i = 0, argLength = 开发者_StackOverflow社区arguments.length; i <argLength; i++) {
var el = arguments[i],
$scrollElement = $(el);
if ($scrollElement.scrollTop()> 0) {
return el;
} else {
$scrollElement.scrollTop(1);
var isScrollable = $scrollElement.scrollTop()> 0;
$scrollElement.scrollTop(0);
if (isScrollable) {
return el;
}
}
}
return [];
}
Notice the offset -60 and for me to not have the jitter, I set the hash to be different from the ID, which is something I don't want at all...
var targetOffset = $target.position().top - 60;
&
location.hash = target+"-section"
I'd like the hash to stay the same, but I do that so the offset is working. Any help would be appreciated.
Simplify your life: http://plugins.jquery.com/project/ScrollTo
It has an offset capability and you just point it at the element itself.
This looks to be exactly like your updated reference to MooTools' SmoothScroll. ScrollTo is exactly what you need.
精彩评论