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;
}正在停止滚动的正常操作,并导致第二个链接滚动到随机位置
发布于 2021-07-22 03:12:44
这里有一个CSS声明可能会有所帮助:
.your-anchor-element-class {
scroll-margin-top: 36px; // <-- your value here
}浏览器支持:在Chrome,FF,Edge,Opera中工作。在带有scroll-snap-margin-top的Safari中受支持。
感谢Josh Comeau指出了这一点。
https://stackoverflow.com/questions/68469660
复制相似问题