我的目标是将粘性 div 最初设置为可见性:隐藏。滚动超过 200 像素后,按钮应显示为可见性:可见。有没有一种解决方法可以仅使用 CSS 而无需 JavaScript 来实现此目的?在纯 CSS 中,似乎没有办法检测像 200px 这样的精确滚动距离。有什么建议吗?
这是我的例子:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<style>
body {
margin: 0;
padding: 0;
}
header {
height: 150px;
background-color: black;
}
.container {
height: 1500px;
background-color: azure;
}
footer {
height: 500px;
background-color: grey;
}
.sticky {
display: flex;
justify-content: flex-end;
position: sticky;
bottom: 10px;
margin:10px;
}
.sticky a {
background-color: black;
color: #fff;
padding: 5px;
}
</style>
</head>
<body>
<header></header>
<div class="container"></div>
<div class="sticky">
<a href="#top">ScrollToTop</a>
</div>
<footer></footer>
</body>
</html>
我尝试了很多东西,比如粘性垫片、具有多个元素的半粘性等等。不幸的是,没有任何效果。
可以类似实现,但是自己调整一下。
body {
margin: 0;
padding: 0;
position: relative;
}
header {
height: 150px;
background-color: black;
}
.container {
height: 200vh;
background-color: azure;
}
footer {
height: 500px;
background-color: grey;
}
.sticky {
display: flex;
justify-content: flex-end;
position: sticky;
bottom: 10px;
margin: 10px;
}
.sticky a {
background-color: black;
color: #fff;
padding: 5px;
bottom: 10px;
/* scroll animation */
view-timeline-name: --subjectReveal;
animation-timeline: --subjectReveal;
animation-name: appear;
animation-fill-mode: both;
animation-duration: 1ms;
}
/* scroll animation */
@keyframes appear {
39% {
opacity: 0;
transform: scaleX(0);
}
40% {
opacity: 1;
transform: scaleX(1);
}
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="test.css">
</head>
<body>
<header></header>
<div class="container"></div>
<div class="sticky">
<a href="#top">ScrollToTop</a>
</div>
<footer></footer>
</body>
</html>
变得简单又准确。
const scrollToTopBtn = document.querySelector('.sticky a');
window.addEventListener('scroll', () => {
if (window.scrollY > 200) {
scrollToTopBtn.classList.add('visible');
} else {
scrollToTopBtn.classList.remove('visible');
}
});
body {
margin: 0;
padding: 0;
}
header {
height: 150px;
background-color: black;
}
.container {
height: 200vh;
background-color: azure;
}
footer {
height: 500px;
background-color: grey;
}
.sticky {
display: flex;
justify-content: flex-end;
position: sticky;
bottom: 10px;
margin: 10px;
}
.sticky a {
opacity: 0;
visibility: hidden;
background-color: black;
color: #fff;
padding: 5px;
transition: .3s;
}
.sticky a.visible {
opacity: 1;
visibility: visible;
}
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<title>Scroll to Top 버튼</title>
</head>
<body>
<header></header>
<div class="container"></div>
<div class="sticky">
<a href="#top">ScrollToTop</a>
</div>
<footer></footer>
</body>
</html>