遠非完美,但爲我工作。 不要忘記使用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 **。 –
我最終調整了我的計劃並找到了另一種解決方法,不過謝謝你的詳細解答。 –