远非完美,但为我工作。 不要忘记使用jQuery。
有它的乐趣:
jQuery('a').on('click',function (e) {
var current = window.location.href.split('#')[0];
var goto = jQuery(this).attr('href').split('#')[0];
if (current == goto && this.hash) {
e.preventDefault();
var target = this.hash;
var $target = jQuery(target);
if($target.length){
jQuery('html,body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing');
}
}
});
jQuery('a[href^=#]:not([href=#])').on('click',function (e) {
e.preventDefault();
var target = this.hash;
var $target = jQuery(target);
if($target.length){
history.pushState(null, jQuery('#title').html() , target);
jQuery('html,body').stop().animate({
'scrollTop': $target.offset().top }, 900, 'swing');
}
});
jQuery('a[href=#]').on('click',function (e) {
e.preventDefault();
history.pushState(null, jQuery('#title').html() , location.href.replace(location.hash,""));
jQuery('html,body').stop().animate({
'scrollTop': 0
}, 900, 'swing');
});
ŧ hanks拉胡尔,但只是测试,看看散列是强者的第一个字符是不够的。这些是CMS页面,导航链接在每个页面上都有相同的URL。在主页上,这些链接将锚定在同一页面上,在其他页面上锚定在主页上。所以哈希不会在一开始。我需要可靠地测试href是否会转到当前页面或转到其他页面。 –
@BenekLisefski请在上面的答案中结帐**更新1 **。 –
我最终调整了我的计划并找到了另一种解决方法,不过谢谢你的详细解答。 –