javascript jQuery 如何不断检查元素是否隐藏/可见?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8713388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery how to constantly check if element is hidden/visible?
提问by Wordpressor
I have a couple of HTML5 videos on my website (within a slider), they automatically cycle every x seconds (or when user clicks "next slide").
我的网站上有几个 HTML5 视频(在滑块内),它们每 x 秒自动循环一次(或当用户单击“下一张幻灯片”时)。
I want to stop the videos that are actually invisible to user, any ideas how to achieve that?
我想停止用户实际上看不到的视频,有什么想法可以实现吗?
I was tryng to do something like that, but I guess there's "each" missing and it works after click instead all the time (ok, in fact it doesn't work because "this" is used wrong here I guess, but you get the point, sorry, I'm not a JS-guy at all :():
我正在尝试做类似的事情,但我想缺少“每个”并且它一直在单击后起作用(好吧,实际上它不起作用,因为我猜在这里使用了错误的“这个”,但是你得到了重点是,抱歉,我根本不是 JS 人 :():
document.on('click', ".videojs:hidden", function(){
alert('video hidden!');
jQuery(this).player.pause();
});
采纳答案by bardiir
You might want to look into this:
你可能想看看这个:
http://www.west-wind.com/weblog/posts/2008/Sep/12/jQuery-CSS-Property-Monitoring-Plugin-updated
http://www.west-wind.com/weblog/posts/2008/Sep/12/jQuery-CSS-Property-Monitoring-Plugin-updated
You can then do something like this:
然后你可以做这样的事情:
jQuery(".videojs").watch("display,visibility", function() {
if(!jQuery(".videojs").is(':visible'))
{
alert('video hidden!');
jQuery(".videojs").player.pause();
}
});
回答by super_seabass
I think you want to look into using setInterval(). Something like:
我认为您想考虑使用setInterval()。就像是:
var videoInterval = setInterval(function() {
// video check logic here
}, 1000);
The above code will run your video check every second (1000 milliseconds). You can probably also use $(
instead of jQuery(
. The videoInterval
variable will let you use clearInterval()
if you need to stop the "loop" of checks for any reason. I believe this code will need to be inside of your $(document).ready(function() {...})
block.
上面的代码将每秒(1000 毫秒)运行一次视频检查。您可能也可以使用$(
代替jQuery(
. 如果您出于任何原因需要停止检查的“循环”,该videoInterval
变量将允许您使用clearInterval()
。我相信这段代码需要在你的$(document).ready(function() {...})
块内。