My web page has 5 videos on it. Only when you hover over the video will it begin to play. My code for this is as follows:
我的网页上有5个视频。只有当您将鼠标悬停在视频上时才会开始播放。我的代码如下:
$(".service:nth-child(1) a").hover(function(){
$('.service:nth-child(1) a video#bgvid').get(0).play();
},function(){
$('.service:nth-child(1) a video#bgvid').get(0).pause();
});
I have used :nth-child
because if I hover over video 4, it plays video 1 so I have to be specific. This means I have to repeat the above code for every video but change the :nth-child
number accordingly. I'm not particularly skilled with JS but there has to be a better and more efficient way of doing this?
我使用过:nth-child因为如果我将鼠标悬停在视频4上,它会播放视频1,所以我必须具体。这意味着我必须为每个视频重复上述代码,但相应地更改:nth-child数字。我对JS不是特别熟练,但必须有更好,更有效的方法吗?
2 个解决方案
#1
Untested but this
should get you started. Ha, a pun. this
. Get it?
未经测试,但这应该让你开始。哈,一个双关语。这个。得到它?
$('.service a').hover(function(){
$(this).children('video').get(0).play();
}, function(){
$(this).children('video').get(0).pause();
});
See also: https://*.com/a/28443915/362536
另见:https://*.com/a/28443915/362536
#2
Like brad said, using this
will allow you to get the currently hovered element. However, afaik jQuery doesn't give you access to the HTML5 video API through their object, so you'd need to do something like:
就像布拉德说的那样,使用它可以让你获得当前悬停的元素。但是,afaik jQuery不允许您通过对象访问HTML5视频API,因此您需要执行以下操作:
$('.service a video').hover(function(e){
e.target.play();
}, function(e){
e.target.pause();
});
When you bind a function to an event, this
will always be the object on which the event was triggered. Calling $(this)
returns a jQuery'd object
将函数绑定到事件时,这将始终是触发事件的对象。调用$(this)会返回一个jQuery对象
#1
Untested but this
should get you started. Ha, a pun. this
. Get it?
未经测试,但这应该让你开始。哈,一个双关语。这个。得到它?
$('.service a').hover(function(){
$(this).children('video').get(0).play();
}, function(){
$(this).children('video').get(0).pause();
});
See also: https://*.com/a/28443915/362536
另见:https://*.com/a/28443915/362536
#2
Like brad said, using this
will allow you to get the currently hovered element. However, afaik jQuery doesn't give you access to the HTML5 video API through their object, so you'd need to do something like:
就像布拉德说的那样,使用它可以让你获得当前悬停的元素。但是,afaik jQuery不允许您通过对象访问HTML5视频API,因此您需要执行以下操作:
$('.service a video').hover(function(e){
e.target.play();
}, function(e){
e.target.pause();
});
When you bind a function to an event, this
will always be the object on which the event was triggered. Calling $(this)
returns a jQuery'd object
将函数绑定到事件时,这将始终是触发事件的对象。调用$(this)会返回一个jQuery对象