【问题标题】:Change Div display element on scroll滚动时更改 Div 显示元素
【发布时间】:2021-05-10 18:26:54
【问题描述】:

大家好,我在一个项目中有一个 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 过渡到其全高。

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

【问题讨论】:

    标签: javascript jquery css jquery-animate css-animations


    【解决方案1】:

    您可以通过在滚动时将class 添加到#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

    【讨论】:

    • 感谢@Manas!这很好用,我确实在 CSS 中添加了一个高度元素,因为使用 visibility=hidden 时,div 仍然“可见”。感谢您的快速响应!
    • @kinzito17 是的,你是对的,它仍然是“可见的”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-16
    • 2010-09-20
    • 1970-01-01
    相关资源
    最近更新 更多