当一个类出现在ViewPort中时,jQuery隐藏[关闭]

问题描述 投票:-1回答:1

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

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

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

javascript jquery
1个回答
1
投票

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

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

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

以下是解决问题的代码:

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>
© www.soinside.com 2019 - 2024. All rights reserved.