我正在使用以下 js 实现页面内页面 anchor 的平滑滚动:
$(document).ready(function() {
$("a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash;
});
}
});
});
在我想使用按钮 + 链接之前,它工作正常。例如,我有一个按钮:
<button onclick="location.href='#anchor'" class="button">Name</button>
我尝试使用上面的函数,比如将 $("a")... 更改为按钮中的类或 id,即 $(".button")... 但事实并非如此做任何事情。不幸的是,我的 js 知识到此为止。有谁知道这是否可能?谢谢!
最佳答案
问题是您正在立即更改按钮中的 href。
试试这个:
<button data-hash="anchor" class="button" type="button">Name</button>
$(document).ready(function() {
$("button.button").on('click', function(event) {
var hash = $(this).data("hash");
if (hash) {
$('html, body').animate({
scrollTop: $(document.getElementById(hash)).offset().top
}, 800, function() {
window.location.hash = hash;
});
}
});
});
关于javascript - 平滑滚动+按钮 'onclick' 功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50648559/