javascript - 平滑滚动 ID 数组
问题描述
我想使用 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 上工作;当我对主使用循环时,它不能正常工作。还有其他方法吗?我可以使动画适用于所有链接,但是如何为某些链接设置例外?
解决方案
稍微改变了你的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 - 从 JavaScript 中的模块导入模块的正确方法是什么?
- javascript - 如何在 Angular JS 的自定义标签中访问 HTML?
- javascript - JavaScript映射返回对象数组而不是ojbect
- amazon-web-services - CloudFormation 堆栈错误 - GetObject 时发生错误。S3 错误代码:NoSuchKey
- android - Firebase Analytics 显示的数据不准确
- laravel - 得到错误'试图获取非对象的属性'id''即使 dd 函数正确返回
- c# - 工厂设计模式(不同签名)
- python - 无法将一些难以辨认的内容处理为可读
- php - 如何使用 SQL 连接合并表?
- c++ - Qt 应用程序意外 LanguageChange 事件