我试图编写一个平滑的滚动函数,可以处理href是否需要先加载新页面然后运行滚动。
我已经看到了向href添加/page-template.html#anchor
的几个选项,但是主页网址只有/#anchor
的动态网站。
所以下面的代码并没有将斜杠视为目标href的一部分。
const $anchor = $('a')
$anchor.on('click', function(event) {
if (this.hash !== "") {
event.preventDefault()
let hash = this.hash
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash
})
}
})
答案 0 :(得分:0)
找到了实现这一目标的方法,但它并不是非常漂亮。任何关于改进它的建议都将受到赞赏。
// If loading a page with a hash in the URL, scroll to it
if (window.location.hash) {
setTimeout(function() {
$('html, body').scrollTop(0)
$('html, body').animate({
scrollTop: $(window.location.hash).offset().top
}, 1000)
}, 0)
}
// Get the current url path
const currUrl = window.location.pathname
$anchor.on('click', function(e) {
// Get the href and a hash into variables
const href = $(this).attr('href')
const hash = this.hash
// If a hash is present
if (hash) {
// Check if there is a URl path before the hash
if (href.charAt(0) !== '#') {
// Check if this URL path matches the current page's href
if (currUrl == href.split('#')[0]) {
e.preventDefault()
// As they match, just run the scroll within the same page
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash
})
}
// There is no URL accompanying the hash, so it's got to be within the same page
} else {
e.preventDefault()
// Run smooth scrolling within the page
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash
})
}
}
})