在触摸设备上清理HTML5视频

时间:2019-04-02 16:16:07

标签: javascript video

如何优化擦洗触摸屏设备视频的过程? 对于鼠标,使用mousedown mousemove事件,一切都可以成功进行。但是在iPad上无法进行擦洗。

var paused;
var shiftX;

progressBar.addEventListener('mousedown', startScrubbing);

function startScrubbing(e) {
    paused = video.paused;
    if (!paused) video.pause();
    shiftX = e.pageX - e.offsetX;
    scrubbing(e);
    document.addEventListener('mousemove', scrubbing);
    document.addEventListener('mouseup', stopScrubbing);
}

function scrubbing(e) {
    video.currentTime = ((e.pageX - shiftX) / progressBar.offsetWidth) * video.duration;
}

function stopScrubbing() {
    document.removeEventListener('mousemove', scrubbing);
    document.removeEventListener('mouseup', stopScrubbing);
    if (!paused) video.play();
}

CodePen上的示例

1 个答案:

答案 0 :(得分:0)

触摸屏必须使用事件:touchstart,touchmove,touchend。而且我什么也没有使用实验参数e.offsetX,触摸事件不会返回该参数。要监听多个事件,请使用jQuery中的.on。这是最终代码:

var paused;
var shiftX = progressBar.getBoundingClientRect().left;

$('.progress-bar').on('mousedown touchstart', function(e) {
    paused = video.paused;
    if (!paused) video.pause();
    scrubbing(e);
    $(document).on('mousemove touchmove', scrubbing);
    $(document).on('mouseup touchend', function() {
        $(document).off('mousemove touchmove');
        $(document).off('mouseup touchend');
        if (!paused) video.play();
    });
});

function scrubbing(e) {
    video.currentTime = ((e.pageX - shiftX) / progressBar.offsetWidth) * video.duration;
}

CodePen