简体   繁体   English

jQuery视频悬停优化动态选择器

[英]jQuery video hover optimising dynamic selectors

I'm working on something where the user hovers over a video to trigger it playing. 我正在研究用户将视频悬停在视频上以触发其播放。 When they hover over a different video, this new video starts playing and stops the others. 当他们将鼠标悬停在其他视频上时,该新视频将开始播放,而其他视频则停止播放。

I'm using Vimeo and their Froogaloop library ( not too relevant here, could also be video tags, mainly concerned with the caching of the selectors ). 我正在使用Vimeo及其Froogaloop库(此处不太相关,也可以是视频标签,主要与选择器的缓存有关)。

This code works fine, but I know it's not as optimised as it should be, it uses multiple selectors each time the hover function is called which I don't want to do. 这段代码可以正常工作,但是我知道它并没有得到应有的优化,每次调用悬停函数时,它都会使用多个选择器,而我不想这样做。 Can I improve this code so that it doesn't do this? 我可以改进此代码,使其不能执行此操作吗? Or is it Ok to keep calling the jQuery selectors like this in modern browsers now? 还是现在可以在现代浏览器中继续像这样调用jQuery选择器?

Here is a simplified working demo 这是一个简化的工作演示

function hoverVid() {
  var frame = $(this).find('iframe');
  var player = $f(frame[0]);
  player.api('play');

  var vids = $('.vid-row iframe').not(frame);
  vids.each(function(index) {
    var frame = $(this);
    var player = $f(frame[0]);
    player.api('pause');
  });
}

$('.vid-row').hover(hoverVid);

Cheers :] 干杯:]

I improved it a bit - As per @GerardCuadras comment, removed the need for using the .not() filter by simply pausing all the videos, then playing the desired one. 我进行了一些改进-根据@GerardCuadras的注释,只需暂停所有视频,然后播放所需的视频,就无需使用.not()过滤器。

This allowed me to cache the list of iframes. 这使我可以缓存iframe列表。 I also optimised the selector to use an #id and .find(). 我还优化了选择器以使用#id和.find()。

JSBin 联合会

var vidz = $('#vidz').find('iframe');

function hoverVid(e){

  vidz.each(function( index ){
    var frame = $(this);
    var player = $f(frame[0]);
    player.api('pause');
  });

  var frame = $(this).find('iframe');
  var player = $f(frame[0]);
  player.api('play'); 
}

$('.vid-row').hover(hoverVid);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM