2017-07-05 41 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