jquery - div进入视口后如何添加类,div离开视口后如何删除类?
问题描述
我希望添加“不透明度”类来列出项目,因为 div 的顶部在视口中变得可见,并在 div 离开视口后删除该类。
我相信它会包含这个 jquery 我只是无法根据视口中的 div 位置确定什么函数会触发这些动作
$('.div-one').addClass('opacity');
}
else{
$('.div-one').removeClass('opacity');
}
});
这是我的代码
HTML
<div class="container">
<div class="wrapper">
<ul>
<div class="one">
<li>Div One</li>
<div>
<div class="two">
<li>Div Two</li>
</div>
<div class="three">
<li>Div Three</li>
</div>
<div class="four">
<li>Div Four</li>
</div>
<div class="five">
<li>Div Five</li>
</div>
</ul>
</div>
<div class="image-div">
<div class="div-one">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSdQoevUP6DXp2yIhVspPDq8el3PTNKpOfwJ-V6my_0Mzd2Rs0x"/>
</div>
<div class="div-two">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRWSzMWTzcJSQdlbu60e0_HK8QntmkoQWrpa1tVjc4EJ7YEDcbHgw"/>
</div>
<div class="div-three">
<img src="http://ftadjusting.com.au/adjusting/wp-content/uploads/2015/09/tl5za8a.png"/>
</div>
<div class="div-four">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSIlN2dswdMe3p6mN9LOznw6IiKh26pkCUMnVdf75nMCFsICqY5"/>
</div>
<div class="div-five">
<img src="https://static-media.fxx.com/img/FX_Networks_-_FXX/684/907/Simpsons_12_06_P1_640x360_316723267976.jpg"/>
</div>
</div>
</div>
CSS
.wrapper {
position: fixed;
}
.image-div {
float: right;
width: 50vw;
}
.image-div img {
width: 50vw;
}
.image-div div {
padding-bottom: 500px;
}
.wrapper ul li {
list-style: none;
margin: 0;
padding: 0;
font-size: 3em;
}
.opacity {
opacity: 0.4;
-webkit-transition: all 0.3 ease;
transition: all 0.3 ease;
}
解决方案
你不需要 jQuery。您可以使用一些简单的 javascript 本身来做到这一点。
希望这可以帮助:
var isInViewport = function (elem) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
var h1 = document.querySelector('h1');
window.addEventListener('scroll', function (event) {
if (isInViewport(h1)) {
console.log("Found...")
}else{
console.log('Missing..')
}
}, false);
body{
overflow: scroll;
height: 200vh;
}
<h1>Header</h1>
您现在可以使用isInViewport条件来设置元素的不透明度。
推荐阅读
- matlab - 使用 fsolve 查找根
- c# - 我如何使它在 UI 打开时我的角色/相机停止移动?
- jquery - Net Core 控制器未接收到 ajax 数据
- c - Execv 系统调用程序没有得到争论
- python - 我如何从 Opencv 获取最新的输出文件
- postman - 为什么 Postman 会忽略变量中的协议和端口号?
- list - python 3,比较两个列表的元素
- python - 如何在python中将多个变量写入.txt文件?
- swift - 如何修复 macOS 的 AppStore 拒绝“您的应用请求管理员访问权限才能运行”
- java - 如何将 Mockito.spy 与匹配器一起使用?