简体   繁体   中英

Animation for div when it enters the viewport horizontally

I'm creating an infinite horizontal feed where I want to animate the element when it enters the viewport horizontally. I'm trying waypoint.js for this.

JS FIDDLE

<div id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
</div>

Adding .show to div which will change opacity of div from 0 to 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;
}

But now the elements would not change their opacity from 0 to 1 when they enter the viewport horizontally. Any idea why? Sorry, I'm really new to javascript and waypoint.

The 100% width is incorrect; if you change it to 500px (the specified width of the individual items), it will work. This is non-optimal though (you will need to update both the JS and CSS whenever you change anything): a better approach would probably be to get the width of the items via JS, and use that value as the offset.

Percentage values passed to offset are percentages of the viewport, which I assume is not what you want here, rather the offset should be ~the width of each item. At the minute, any item even partially within the viewport is opaque, so you never see any change.

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

this inside the waypoint handler is not the element, it is the Waypoint instance. You want to use $(this.element).addClass('show')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM