javascript - 滚动时更改 Div 显示元素
问题描述
大家好,我在一个项目中有一个 div,display=none
直到它到达某个滚动位置然后它变为display=block
.
这很有效,而且很棒,但变化的突然性不是那么好。我想找到一种方法让它轻松查看,比如 50 像素。
我正在寻找的 div 具有这种结构
<div class=section id=anchoredCtaWeb>
<div class=container>
<h1>Hello World</h1>
</div>
</div>
这是我目前应用的样式和JS
<style>
#anchoredCtaWeb {
display: none;
position: sticky;
top: 0px;
}
</style>
<script>
document.addEventListener("scroll", function() {
if (window.pageYOffset > 817)
document.getElementById('anchoredCtaWeb').style.display = "block";
if (window.pageYOffset < 817)
document.getElementById('anchoredCtaWeb').style.display = "none";
});
</script>
我知道它的表现方式正是我所写的,但我没有成功将高度从 0px 转换为全高。
我非常感谢任何反馈,谢谢!
解决方案
您可以通过在滚动上添加class
to来做到这一点。#anchoredCtaWeb
document.addEventListener("scroll", function() {
const anchoredCtaWeb = document.getElementById("anchoredCtaWeb");
if (window.pageYOffset > 817) {
anchoredCtaWeb.classList.add("show");
}
if (window.pageYOffset < 817) {
anchoredCtaWeb.classList.remove("show");
}
});
body {
height: 600vh;
}
#anchoredCtaWeb {
position: sticky;
transform: translateY(50px);
opacity: 0;
visibility: hidden;
top: 10px;
}
#anchoredCtaWeb.show {
transform: translateY(0px);
opacity: 1;
visibility: visible;
transition: 0.5s ease-in-out;
}
<div class="section" id="anchoredCtaWeb">
<div class="container">
<h1>Hello World</h1>
</div>
</div>
在 Codepen 上检查它:https ://codepen.io/manaskhandelwal1/pen/yLVOMPE
推荐阅读
- angular - Web Audio API getByteTimeDomainData 返回平面 128(全为零)
- file - 在 svelte 中显示文件内容
- angular - 如何在星云中没有全局微调器的情况下导航?
- python - 在 Python 中处理执行的系统命令错误
- c# - C# - “非空”条件的级联
- javascript - 如何在 React 中创建新行?
- python - 在 ElasticSearch 中,如何搜索大量关键字
- java - 将 java 从 MainActivity.java 移动到 HomeFragment.java 导致错误认为相同的代码
- c++ - 为散列函数定义一个 c++20 概念
- regex - Nginx 正则表达式