首页 > 解决方案 > 滚动时更改 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 转换为全高。

我非常感谢任何反馈,谢谢!

标签: javascriptjquerycssjquery-animatecss-animations

解决方案


您可以通过在滚动上添加classto来做到这一点。#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


推荐阅读