【发布时间】:2021-07-21 12:40:29
【问题描述】:
Javascript 新手,在这个问题上花了几个小时:/
我想实现平滑的滚动效果以移动到网页的不同部分。我正在使用这段 javascript。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('a').on('click', function(e) {
if (this.hash !== '') {
e.preventDefault();
const hash = this.hash;
$('html, body, .main')
.animate({
scrollTop: $(hash).offset().top
}, 800);
}
});
这是基本结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="margin-left: 30%; margin-right: 30%">
<main>
<a href="#contactme"><div class="contactme-button">Contact me</div></a>
<div class="section-1" style="width: 100%; height: 1000px; background-color: grey; display: block;"> </div>
<a href="#contactme"><div class="contactme-button-2">Contact me</div></a>
<div class="section-1" style="width: 100%; height: 1000px; background-color: blue; display: block;"> </div>
<div class="contactme-section" id="contactme" style="width: 100%; height: 100px; background-color: grey;">CONTACT ME</div>
<div class="section-1" style="width: 100%; height: 1000px; background-color: black; display: block;"> </div>
</main>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$('a').on('click', function(e) {
if (this.hash !== '') {
e.preventDefault();
const hash = this.hash;
$('html, body, .main').animate({
scrollTop: $(hash).offset().top
}, 800);
}
});
</script>
</html>
(里面有更多内容,但这是让我伤心的基本结构)
我发现
.main{
overflow-x: hidden;
}
正在停止滚动的正常操作并导致第二个链接滚动到随机点
【问题讨论】:
-
您能否提供一个关于 Codesandbox、Codepen、Stack Overflow 代码 sn-p 或类似环境的最小可重现示例来说明问题并将其添加到您的问题中? stackoverflow.com/help/minimal-reproducible-example
-
更新问题
标签: smooth-scrolling