我想将当前时间和持续时间转换为百分比



嘿,所以我想按百分比监控视频播放的进度,以便当用户观看 25、50 和 75% 的用户发送警报时。这就是我目前所拥有的。

var Currenttime1 = document.getElementById('video').attr('currenttime');
var Duration1 = document.getElementById('video').attr('duration');
console.log(Currenttime1);
console.log(Duration1);

function percenttime(){

                var timemonitored = Duration1/Currenttime1 *100;
                var alertsSent = 0;
                if(timemonitored > 25 && alertsSent == 0)
                {
                console.log(timemonitored);
                    alert("player has reached 25%");
                    alertsSent++;
                }
                else if(timemonitored > 50 && alertsSent == 1)
                {
                    alert("player has reached 50%");
                    alertsSent++;
                }
                else if(timemonitored > 75 && alertsSent == 2)
                {
                    alert("player has reached 75%");
                    alertsSent++;
                }
            }

我错过了什么吗?我放入控制台.log以查看持续时间 1、当前时间 1 和时间监控中的内容,但它没有填充值。这是小提琴链接。http://jsfiddle.net/Ypczm/

  1. 检查你的语法,你的变量有时是大写的,有时不是
  2. 加载 jQuery...
  3. 您正在定义函数,但从不调用它。您希望此函数何时运行?

一种方法是创建一个间隔函数,该函数每 1000 毫秒触发一次,并使用 jQuery 获取当前的播放时间。

编辑:使用 jQuery 使用 JS:

$(function() {
    var vid = $('#video'),
        check,
        reached25 = false,
        reached50 = false,
        reached75 = false;
    vid.bind("play", function(event) {
        var duration = vid.get(0).duration;
        check = setInterval(function() {
                var current = vid.get(0).currentTime,
                    perc = (current / duration * 100).toFixed(2);

                if (Math.floor(perc) >= 25 &&! reached25) {
                    console.log("25% reached");
                    reached25 = true;
                }
                console.log(perc);
        }, 1000);
    });
    vid.bind("ended pause", function(event) {
        clearInterval(check);
    });
});

JSFiddle

您有多个语法错误:

console.log(Currenttime1)
                         ^--missing semi-colons (and on other lines as well)
console.log(duration1)
            ^---not capitalized

如果你费心查看浏览器的Javascript控制台(例如Firefox中的shift-ctrl-J),你会看到JS语法错误,这些错误已经完全杀死了整个代码块。

现在我看到你偷偷编辑掉了D vs.s. d错误,但没关系...分号业务仍然存在。

最新更新