随着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;
}
答案 0 :(得分:0)
您不需要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 条件设置元素的不透明度。