2017-07-05 55 views
0

我跟隨this guide來檢測我的視頻元素何時進入視口,然後執行「x」,但不斷收到標題錯誤。不知道是否因爲我使用wordpress與吞噬和piling.js不受支持的僞:在視口中

我的頁面使用打樁,我有一個視頻部分,當我滾動到「堆棧」,我想視頻開始播放,但它開始播放頁面加載。

// inside document.ready() 

$('video').each(function(){ 
    if ($(this).is(":in-viewport")) { 
     $(this)[0].play(); 
    } else { 
     $(this)[0].pause(); 
    } 
}) 

Uncaught Error: Syntax error, unrecognized expression: unsupported pseudo: in-viewport

<div id='<ID-CHANGES-INSIDE-LOOP>' class='image-block'> 
    <video autoplay> 
    <source class='video' src='movie.mp4' type='video/mp4'> 
    </video> 
</div> 

是採用打樁做出這一困難的工作?

回答

0

:in-viewport需要通過一個插件(我再也找不到)附僞屬性 -

也許嘗試嘗試OnScreen基本能見度檢測,而不是;它大致相同。

2

該僞選擇器需要其插件才能工作(它不是jQuery選擇器的一部分),但是現在您可以使用.getBoundingClientRect()輕鬆檢查元素是否位於視口中。這裏的方法我用:

/** 
* Check if an element is in the visible viewport 
* @param {jQuery|HTMLElement} el 
* @return boolean 
*/ 
var IsInViewport = function(el) { 
    if (typeof jQuery === "function" && el instanceof jQuery) el = el[0]; 
    var rect = el.getBoundingClientRect(); 
    return (
     rect.top >= 0 && 
     rect.left >= 0 && 
     rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && 
     rect.right <= (window.innerWidth || document.documentElement.clientWidth) 
    ); 
}; 

// example 
if(IsInViewport($('#myvideo'))) { /* do stuff.. */ } 

另外,根據您的需求,您可以使用:visible選擇(https://api.jquery.com/visible-selector/)。

+0

嗨。我得到'無法讀取屬性'未定義的getBoundingClientRect'。我的錯。是的,這工作。 Thnaks – Sylar

+0

如何不在視圖端口? – Sylar

+0

我正在尋找一個我之前做過的例子,它與您正在尋找的相匹配。希望它適合你:https://jsfiddle.net/3frk6u58/ – kosmos