div 水平进入视口时的动画

问题描述 投票:0回答:3

我正在创建一个无限水平提要,我想在元素水平进入视口时为其设置动画。我正在为此尝试 waypoint.js。

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 还很陌生。

javascript jquery jquery-waypoints
3个回答
0
投票

100%宽度不正确;如果将其更改为 500px(单个项目的指定宽度),它将起作用。但这不是最佳选择(每当您更改任何内容时,您都需要更新 JS 和 CSS):更好的方法可能是通过 JS 获取项目的宽度,并使用该值作为偏移量。

传递给

offset

 的百分比值是视口的百分比,我认为这不是您想要的,而偏移量应该是〜每个项目的宽度。目前,任何项目(即使部分位于视口内)都是不透明的,因此您永远看不到任何变化。

参见

http://imakewebthings.com/waypoints/api/offset-option/


0
投票

this

 不是元素,而是 Waypoint 实例。您想使用
$(this.element).addClass('show')

    


0
投票

JsFiddle 演示 代码中的问题在于,在

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>

© www.soinside.com 2019 - 2024. All rights reserved.