hover时的video播放
我有一系列video缩略图,我想在hover时触发播放/暂停。 我设法让其中一个工作,但我遇到了列表中其他人的问题。 附件是我的代码的小提琴。 将有一个div覆盖每个html5video,因此hover需要委托给video,我不确定如何做。
http://jsfiddle.net/meh1aL74/
在这里预览html –
在这里预览javascript –
var figure = $(".video"); var vid = $("video"); [].forEach.call(figure, function (item) { item.addEventListener('mouseover', hoverVideo, false); item.addEventListener('mouseout', hideVideo, false); }); function hoverVideo(e) { $('.thevideo')[0].play(); } function hideVideo(e) { $('.thevideo')[0].pause(); }
非常感谢您的帮助。
奥利弗
你为什么要用jQuery绑定原生事件?
无论如何,如果你想本地处理事件,你可以使用.bind
方法并将每个video的索引传递给处理程序
var figure = $(".video"); var vid = figure.find("video"); [].forEach.call(figure, function (item,index) { item.addEventListener('mouseover', hoverVideo.bind(item,index), false); item.addEventListener('mouseout', hideVideo.bind(item,index), false); }); function hoverVideo(index, e) { vid[index].play(); } function hideVideo(index, e) { vid[index].pause(); }
演示http://jsfiddle.net/gaby/0o8tt2z8/2/
或者你可以去完整的jQuery
var figure = $(".video").hover( hoverVideo, hideVideo ); function hoverVideo(e) { $('video', this).get(0).play(); } function hideVideo(e) { $('video', this).get(0).pause(); }
演示http://jsfiddle.net/gaby/0o8tt2z8/1/
最短版本就是这个版本
这样,如果你愿意的话,它会更清洁。
hoverVideo()
函数专门调用.thevideo
的第一个实例,因此将.thevideo
hover在其中任何一个上将播放第一个video。
您必须获取事件发生的元素,然后在该元素中找到.thevideo
元素:
var figure = $(".video"); var vid = $("video"); [].forEach.call(figure, function (item) { item.addEventListener('mouseover', hoverVideo, false); item.addEventListener('mouseout', hideVideo, false); }); function hoverVideo(e) { $(this).find('.thevideo')[0].play(); } function hideVideo(e) { $(this).find('.thevideo')[0].pause(); }
这是一个更新的小提琴: http : //jsfiddle.net/52mxdbgy/1/
你的函数明确要求第一个video: $('.thevideo')[0].play();
(数组中的第一个元素)。
因此,您需要(至少)传递绑定操作的video的索引,以确保播放和暂停正确的video。
例如:
$(document).ready(function() { $('.video').each(function(i, obj) { $(this).on("mouseover", function() { hoverVideo(i); }); $(this).on("mouseout", function() { hideVideo(i); }); }); }); function hoverVideo(i) { $('.thevideo')[i].play(); } function hideVideo(i) { $('.thevideo')[i].pause(); }
我使用jQuery的.on()
方法所以所有方法都是jQuery(而不是与JavaScript的混合)。
你可以在下面的jsFiddle中看到这个:
DEMO
这里没有jQuery和ES6一样。 ;)
for(let tupel of document.querySelectorAll('video')) { tupel.addEventListener('mouseover', (e) => { e.target.play() }, false); tupel.addEventListener('mouseout', (e) => { e.target.pause() }, false); }