javascript - 当一个类出现在 ViewPort 中时 jQuery 隐藏
问题描述
当向下滚动时某个类出现在 ViewPort 中时,我想让 FIXED 按钮消失。
更具体地说,它是一个固定的添加到购物车按钮,当用户向下滚动到产品描述下方显示的静态添加到购物车按钮时,它应该消失。
等待帮助,一定很容易我只是不是很有经验......谢谢!
解决方案
新的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>
推荐阅读
- ios - 导航栏颜色更改未通过 UINavigationBarAppearance() 传递到其他视图
- php - 在 Slim Framerwork 的容器上设置 $app 实例是一种不好的做法吗?
- r - 我在 R2jags 中看不到模型结果 - 出了什么问题?
- laravel - Laravel 8查找方法结果404未找到
- visual-studio-code - 在 VSC 上,我可以复制/粘贴折叠代码并保持折叠状态吗?
- python - FastApi + Gunicorn workers + Google 应用引擎
- authentication - 如何从服务器端访问 grpc 客户端 ssl 证书信息?
- python - 熊猫按时隙计数
- python - 使用 firebase 用户 UID 作为 id 创建 django 用户
- javascript - 在带有选定叠加层名称的传单地图上添加文本框