$('#MyVideo').on(
'timeupdate',
function(event) {
// Save object in case you want to manipulate it more without calling the DOM
$this = $(this);
var state = 0;
if ((this.currentTime > (this.duration - 35)) && (state == 0)) {
state = 1;
console.log(state);
};
//Reset state
if (this.currentTime < (this.duration - 5)) {
state = 0;
}
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box1">
<video width=100% id="MyVideo" preload="auto" autoplay loop muted="muted" volume="0">
<source src="https://emmy-kane-9tej.squarespace.com/s/343731697.mp4" type="video/mp4">
</video>
</div>
&#13;
我有一个循环视频,我想在视频结束时调用fadeOut函数。但是,我的函数被多次调用,并且似乎忽略了状态变量已经改变。我对jQuery很新,所以我可能会遗漏一些非常明显的东西,有没有人知道为什么这段代码会不断发送&#34; 1&#34;到控制台?
答案 0 :(得分:2)
问题是你在函数内部设置状态,然后每次运行函数时都会重置。
您应该做的是将其设置在.on()函数之外,然后再次设置它,除非满足您的条件。
var state = 0;
$('#MyVideo').on(
'timeupdate',
function() {
// Save object in case you want to manipulate it more without calling the DOM
if ((this.currentTime > (this.duration - 35)) && (state == 0)) {
state = 1;
console.log(state);
};
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box1">
<video width=100% id="MyVideo" preload="auto" autoplay loop muted="muted" volume="0">
<source src="https://emmy-kane-9tej.squarespace.com/s/343731697.mp4" type="video/mp4">
</video>
</div>
&#13;
查看这个jsfiddle:https://jsfiddle.net/p98wwe5L/1/
答案 1 :(得分:1)
试试这个
var state = 0;
$('#MyVideo').on(
'timeupdate',
function() {
// Save object in case you want to manipulate it more without calling the DOM
if ((this.currentTime > (this.duration - 35)) && (state == 0)) {
state = 1;
console.log(state);
};
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box1">
<video width=100% id="MyVideo" preload="auto" autoplay loop muted="muted" volume="0">
<source src="https://emmy-kane-9tej.squarespace.com/s/343731697.mp4" type="video/mp4">
</video>
</div>
答案 2 :(得分:0)
var state = 0;
$('#MyVideo').on('timeupdate', function(event) {
if (state == 1 && this.currentTime < this.duration - 5) {
state = 0;
console.log(state);
} else if (state == 0 && this.currentTime > this.duration - 5) {
state = 1;
console.log(state);
// Fade out
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<video width=100% id="MyVideo" preload="auto" autoplay loop muted="muted" volume="0">
<source src="https://emmy-kane-9tej.squarespace.com/s/343731697.mp4" type="video/mp4">
</video>