gpt4 book ai didi

javascript - 平滑滚动 ID 数组

转载 作者:行者123 更新时间:2023-12-03 01:39:59 27 4
gpt4 key购买 nike

我想使用 jQuery 平滑滚动 HTML 网站中的某些链接。

var main = ["#main1", "#main2", "#main3", "#main4"]
$(document).ready(function () {
$("a").on('click', function (event) {
if (this.hash ==|| this.hash == "#top") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function () {
window.location.hash = hash;
});
}
});
});

我需要这个动画在我的主数组和 #top ID 上工作;当我对 main 使用循环时,它将无法正常工作。还有别的办法吗?我可以使动画在所有链接上运行,但如何对某些链接进行异常(exception)处理?

最佳答案

稍微改变一下你的js

$("a").on('click', function(event) {
if (this.hash && main.includes(this.hash)) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash;
});

基本上就是这一行if (this.hash && main.includes(this.hash)) {

$(document).ready(function() {
var main = ["#main1", "#main2", "#main3", "#main4", "#top"];
$("a").on('click', function(event) {
if (this.hash && main.includes(this.hash)) {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function() {
window.location.hash = hash;
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="top">
</div>
<div id="main1" style="height: 200px;background-color:red;">
<a href="#main2">
Go to Main 2
</a>
<br/>
<a href="#main5">
Go to Main 5 withoout animation
</a>

</div>
<div id="main2" style="height: 200px;background-color:skyblue;">
<a href="#main3">
Go to Main 3
</a>
<br/>
<a href="#top">
Go to Top
</a>
</div>
<div id="main3" style="height: 200px;background-color:green;">
<a href="#main4">
Go to Main 4
</a>
<br/>
<a href="#top">
Go to Top
</a>
</div>
<div id="main4" style="height: 200px;background-color:yellow;">
<a href="#main1">
Go to Main 1
</a>

</div>
<div id="main5" style="height: 200px;background-color:red;">
<a href="#main1">
Go to Main 1
</a>

</div>

关于javascript - 平滑滚动 ID 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50894948/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com