首页 > 解决方案 > 当一个类出现在 ViewPort 中时 jQuery 隐藏

问题描述

当向下滚动时某个类出现在 ViewPort 中时,我想让 FIXED 按钮消失。

更具体地说,它是一个固定的添加到购物车按钮,当用户向下滚动到产品描述下方显示的静态添加到购物车按钮时,它应该消失。

等待帮助,一定很容易我只是不是很有经验......谢谢!

标签: javascriptjquery

解决方案


新的Intersection Observer API非常直接地解决了您的问题。

这个解决方案需要一个 polyfill,因为 Safari 和 Opera 还不支持这个。(polyfill 包含在解决方案中)。

在这个解决方案中,有一个看不见的盒子是目标(观察到的)。当它进入视图时,标题顶部的按钮是隐藏的。一旦盒子离开视图,它就会显示出来。

这是解决您的问题的代码:

const buttonToHide = document.querySelector('button');

const hideWhenBoxInView = new IntersectionObserver((entries) => {
  if (entries[0].intersectionRatio <= 0) { // If not in view
    buttonToHide.style.display = "inherit";
  } else {
    buttonToHide.style.display = "none";
  }
});

hideWhenBoxInView.observe(document.getElementById('box'));
header {
  position: fixed;
  top: 0;
  width: 100vw;
  height: 30px;
  background-color: lightgreen;
}

.wrapper {
  position: relative;
  margin-top: 600px;
}

#box {
  position: relative;
  left: 175px;
  width: 150px;
  height: 135px;
  background-color: lightblue;
  border: 2px solid;
}
<script src="https://polyfill.io/v2/polyfill.min.js?features=IntersectionObserver"></script>
<header>
  <button>NAVIGATION BUTTON TO HIDE</button>
</header>
  <div class="wrapper">
    <div id="box">
    </div>
  </div>


推荐阅读