在html中,我有3个ID为“ button”的按钮,分别对应于具有其ID的不同部分 这是脚本,
$(document).ready(function(){
$("#button").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 1500, function(){
window.location.hash = hash;
});
}
});
});
答案 0 :(得分:0)
实际上您不能有多个具有相同ID的元素,每个元素都需要具有不同的ID或相同的类。
尝试提供不同的ID,让我知道它是否有效。
答案 1 :(得分:0)
另一个没有javascript的解决方案是
<html>
<head>
<style>
html{
scroll-behavior: smooth;
}
#sec1, #sec2, #sec3{
height: 100%;
}
</style>
</head>
<body>
<a href="#sec1">Go to one</a> |
<a href="#sec2">Go to two</a> |
<a href="#sec3">Go to three</a><br><br>
<div id="sec1" style="background-color: lightgreen">Section one</div>
<div id="sec2" style="background-color: lightyellow">Section Two</div>
<div id="sec3" style="background-color: lightblue">Section Three</div>
</body>
</html>