我正在尝试找到一个脚本,当它们在滚动时到达屏幕中间时,它们将在页面上播放我的gif。目前,我有此脚本,它可以在进入屏幕视图时立即播放gif。但这并没有给用户足够的时间来播放正在播放的动画。我对此表示感谢。艾米
function isScrolledIntoView(el) {
var rect = el.getBoundingClientRect();
return (rect.middle >= 0) && (rect.bottom <= window.innerHeight);
}
function animateGifsInScreen() {
$('.gif').each(function(index, el) {
if(isScrolledIntoView(el)) {
$(el).trigger('mouseenter');
} else {
$(el).trigger('mouseleave');
}
});
}
$(document).scroll(animateGifsInScreen);
使用github.com/buzzfeed/libgif-js检查此示例,
注意:以全屏模式运行
var sup = [];
var playing = null;
$(function(){
var i = 0;
$('.gif').each(function(){
sup[i] = new SuperGif({ gif:this, progressbar_height: 0,
auto_play: false, } );
sup[i].load();
i++;
});
var findMiddleElement = (function(docElm){
var viewportHeight = docElm.clientHeight,
elements = $('.image-div');
return function(e){
var middleElement;
if( e && e.type == 'resize' )
viewportHeight = docElm.clientHeight;
elements.each(function(){
var pos = this.getBoundingClientRect().top;
// if an element is more or less in the middle of the viewport
if( pos > viewportHeight/2.5 && pos < viewportHeight/1.5 ){
middleElement = this;
return false; // stop iteration
}
});
if(typeof(middleElement)!='undefined'){
var index = $(middleElement).index();
//console.log(index);
if(playing!=index){
if(typeof(sup[index])!="undefined"){
if(typeof(sup[playing])!='undefined'){
sup[playing].pause();
}
playing = index;
sup[playing].play();
}
}
}
}
})(document.documentElement);
$(window).on('scroll resize', findMiddleElement);
});
.image-div{
margin: 25px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://solarisedesign.co.uk/_themes/solarise/js/libgif.js"></script>
<ul>
<li class="image-div">
<img src='https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif' class='gif' />
</li>
<li class="image-div">
<img src='https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif' class='gif' />
</li>
<li class="image-div">
<img src='https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif' class='gif' />
</li>
<li class="image-div">
<img src='https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif' class='gif' />
</li>
<li class="image-div">
<img src='https://media.giphy.com/media/Byana3FscAMGQ/giphy.gif' class='gif' />
</li>
</ul>