我正在创建一个无限水平提要,我想在元素水平进入视口时为其设置动画。我正在为此尝试 waypoint.js。
<div id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>
向 div 添加 .show ,这会将 div 的不透明度从 0 更改为 1。
$(function() {
$(".item").each(function(){
$(this).waypoint(function() {
$(this).addClass('show');
}, {
offset: '100%',
horizontal: true
});
});
});
CSS
.item
{
width:500px;
height:250px;
background:red;
color:#fff;
display:inline-block;
opacity:.2;
}
.item.show
{
opacity:1;
}
但是现在,当元素水平进入视口时,它们的不透明度不会从 0 更改为 1。知道为什么吗?抱歉,我对 javascript 和 waypoint 还很陌生。
this
不是元素,而是 Waypoint 实例。您想使用
$(this.element).addClass('show')
waypoint
回调函数中,
$(this)
指的是 Waypoint 对象,而不是原始的 DOM
元素。要解决此问题,您应该将原始 DOM 元素的引用存储在路径点回调之外
$(function() {
$(".item").each(function() {
var $this = $(this); // Store the reference to the original DOM element
$this.waypoint(function() {
$this.addClass('show'); // Use the stored reference here
}, {
offset: '100%',
horizontal: true
});
});
});
.item {
width: 500px;
height: 250px;
background: red;
color: #fff;
display: inline-block;
opacity: 0.2;
transition: opacity 0.5s ease; /* Add a transition for a smoother effect */
}
.item.show {
opacity: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script>
<div id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>