Jquery 平滑滚动直接调用div
我正在使用此脚本制作一个带有smootscroll的单页网站Jquery 平滑滚动直接调用div,jquery,wordpress,twitter-bootstrap-3,Jquery,Wordpress,Twitter Bootstrap 3,我正在使用此脚本制作一个带有smootscroll的单页网站 $('a[href*=#]:not([href=#])').click(function() { if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { var target = $(this.hash); target = target
$('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 - 125
}, 1000);
return false;
}
}
});
但是,如果我直接使用?page_id=6#apps?调用div,它会忽略
target.offset().top - 125
ik如何修复此问题?使用onhashchange事件查看它是否符合您的需要:
$(function () {
$('a[href*=#]:not([href=#])').click(scrollToElement);
});
$(window).one('hashchange', scrollToElement).on('load', function () {
$(this).triggerHandler('hashchange');
});
function scrollToElement() {
var hash = this.hash ? this.hash : window.location.hash;
var $target = $(hash).length ? $(hash) : $('[name=' + hash.slice(1) + ']');
if ($target.length) {
$('html,body').animate({
scrollTop: $target.offset().top - 125
}, 1000);
return false;
}
}
它正在工作,但它看起来有点奇怪,先是向下滚动,然后向上滚动。我如何改进它?您能提供一个JSFIDLE吗?