问题
I'm trying to get my embedded Vimeo video to pause on exiting the viewport and allow another embedded Vimeo video to play upon entering viewport.
I've been exploring various solutions and discovered Froogaloop which works perfectly, however I believe is the old Vimeo api.
I got an exact example working of the video pausing on exiting, but its using an ID rather than class so unable to use on more than one video and not entirely sure how to accomplish this.
Example - Jsfiddle
<div class="inner">
<iframe id="video" src="https://player.vimeo.com/video/220643186?
autoplay=1&loop=1&color=357ded&title=0&byline=0&portrait=0" width="640"
height="360" frameborder="0" webkitallowfullscreen mozallowfullscreen
allowfullscreen></iframe>
</div>
Jquery :
var iframe = document.getElementById('video');
// $f == Froogaloop
var player = $f(iframe);
var inner = $(".inner");
var elementPosTop = inner.position().top;
var viewportHeight = $(window).height();
$(window).on('scroll', function () {
var scrollPos = $(window).scrollTop();
var elementFromTop = elementPosTop - scrollPos;
if (elementFromTop > 0 && elementFromTop < elementPosTop + viewportHeight) {
inner.addClass("active");
player.api("play");
} else {
inner.removeClass("active");
player.api("pause");
}
});
Any help would be immensely appreciated :)
回答1:
You need different player objects - one for each iframe. For performance reasons you should create the list of players outside of your onScroll function.
var players = []
$('.inner').each(function() {
players.push({
player: new Vimeo.Player($(this).find("iframe").get(0)),
top: $(this).position().top,
status: "paused"
})
});
var viewportHeight = $(window).height();
$(window).on('scroll', function() {
var scrollPos = $(window).scrollTop();
for(var i=0; i<players.length;i++) {
var elementFromTop = players[i].top - scrollPos;
var status = (elementFromTop > 0 && elementFromTop < players[i].top + viewportHeight) ? "play" : "pause";
if(players[i].status != status) {
players[i].status = status;
players[i].player[status]();
console.log(i, status);
}
}
});
You can test here: https://jsfiddle.net/ptc1qy0m/ Note: it is not possible to start any video automatically, if its sound is on. So in this case you have to start each video manually.
来源:https://stackoverflow.com/questions/51689010/vimeo-iframe-play-pause-out-of-viewport