2017-08-14 26 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

相關問題