2017-08-14 25 views
0

如标题中所述,我正在侦听scroll事件,以便在video的30%出现时触发该功能在窗口中 - 无论用户是向上还是向下滚动。如何检查用户是否滚动到元素的30%,从顶部或底部

什么是有是这样的:

// On DOM ready, I set the top and bottom offset of the video, 
// +/- 30% of the video height 

var $video = $('#js-b2b-video'); 
var videoHeight = $video.outerHeight(); 
var videoHeight30 = parseInt(videoHeight/3, 10); // Approx. 30% of the video height 
var videoObj = {} 

videoObj.top = $video.offset().top + videoHeight30; // Approx. 30% from the top of the video 
videoObj.bottom = videoObj.top + videoHeight - videoHeight30; // Approx. 30% from the bottom of the video 

然后,滚动事件:

$(window).on('scroll', function() { 
    if ($(window).scrollTop() >= videoObj.top) { 
     alert('30% from the top of the video reached'); 
    } 
}); 

然而,这触发太晚了,当视频是完全可见。我需要的是当视频的顶部或底部30%可见时立即激活我的功能。

我该如何正确做到这一点?

Fiddle

+2

也许尝试绘制一张图片。 'scrollTop'是视口的顶部,听起来好像你想要检查视口的* bottom *何时已经超过视频高度的30%。 – zzzzBov

回答

0

你需要采取窗口的高度考虑进去。

if ($(window).scrollTop() + $(window).height() >= videoObj.top) { 
0

你可能需要考虑窗口的高度,以及:

if ($(window).scrollTop() + window.innerHeight >= videoObj.top) { 

请注意,您可能需要测试在的onload调整太...

Try it

相关问题