我正在尝试使用 jQuery 绑定(bind) play
/pause
和 ended
事件,但是有一个问题:
当我右键单击视频并选择播放或暂停时,图标会正确更改。当我单击播放按钮时,它会变为暂停,但如果我单击暂停按钮继续播放视频,它不会变为再次播放。
谁能告诉我哪里出错了?
这是我的代码:
var PlayVideo = function () {
if ($('#video').attr('paused') == false) {
$('#video').get(0).pause();
} else {
$('#video').get(0).play();
}
};
$('#playbtn').click(PlayVideo);
$('#video').click(PlayVideo);
$('#video').bind('play', function () {
$('.playbtn').addClass('pausebtn');
});
$('#video').bind('pause', function () {
$('.playbtn').removeClass('pausebtn');
});
$('#video').bind('ended', function () {
$('.playbtn').removeClass('pausebtn');
});
CSS:
.playbtn {
display: block;
width: 32px;
height: 32px;
margin-left: 10px;
background: url('../images/play.png') no-repeat;
opacity: 0.7;
-moz-transition: all 0.2s ease-in-out; /* Firefox */
-webkit-transition: all 0.2s ease-in-out; /* Safari and Chrome */
-o-transition: all 0.2s ease-in-out; /* Opera */
transition: all 0.2s ease-in-out;
}
.pausebtn {
display: block;
width: 32px;
height: 32px;
margin-left: 10px;
background: url('../images/pause.png') no-repeat;
opacity: 0.7;
-moz-transition: all 0.2s ease-in-out; /* Firefox */
-webkit-transition: all 0.2s ease-in-out; /* Safari and Chrome */
-o-transition: all 0.2s ease-in-out; /* Opera */
transition: all 0.2s ease-in-out;
}
最佳答案
HTML5 视频没有pause
属性。相反,您应该看看 media events and properties .
在您的情况下,这意味着:
if (!$('#video')[0].paused) {
$('#video')[0].pause();
} else {
$('#video')[0].play();
}
顺便说一句:由于您经常调用 $('#video')
,因此将其存储在变量中可能是个好主意 - 这样您就不必调用 jQuery-选择器无数次。喜欢:
$video = $('#video'); //from now on just use $video instead of $('#video')
编辑: 关于您的评论,如果没有看到您正在使用的控件(HTML 和 CSS)很难判断,但无论如何您可以对所有事件使用相同的处理程序触发相同的行为(并且由于该行为在 pause
上是正确的,因此当绑定(bind)到同一处理程序时,它也应该在 ended
上)。此外,在您发布的代码中,您在结束时使用了 removeClass
(它可能应该是 addClass
)。所以这应该有效:
$('#video').bind('play ended', function () { //should trigger once on any play and ended event
$('.playbtn').addClass('pausebtn'); //might also be $('#playbtn') ???
});
$('#video').bind('pause', function () { //should trigger once on every pause event
$('.playbtn').removeClass('pausebtn'); //might also be $('#playbtn') ???
});
我注意到的另一个故障是您使用了一次 #playbtn
而另一次使用了 .playbtn
。尝试使用播放按钮执行某些操作时,请确保您在此处指的是相同的项目。
关于jquery - 使用 jQuery 将播放/暂停/结束功能绑定(bind)到 HTML5 视频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9874095/