You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现键盘数字键控制视频快进/后退?尝试代码未生效

解决数字键控制视频跳转的问题

问题根源

你写的case 1无法触发事件,是因为键盘主数字键1对应的keyCode是49,小键盘数字1对应的keyCode是97,而非你用的数字1。

修正代码(支持数字键跳转固定时长)

如果要实现按数字键1快进30秒,其他数字键可依此类推,修正后的代码如下:

var theVideo = document.getElementById("cspd_video");
document.onkeydown = function(event) {
    switch (event.keyCode) {
        case 37: // 左箭头后退5秒
            event.preventDefault();
            theVideo.currentTime = Math.max(0, theVideo.currentTime - 5);
            break;
        case 39: // 右箭头快进5秒
            event.preventDefault();
            theVideo.currentTime = Math.min(theVideo.duration, theVideo.currentTime + 5);
            break;
        case 49: // 主键盘数字1:快进30秒
            event.preventDefault();
            theVideo.currentTime = Math.min(theVideo.duration, theVideo.currentTime + 30);
            break;
        case 50: // 主键盘数字2:快进60秒(示例)
            event.preventDefault();
            theVideo.currentTime = Math.min(theVideo.duration, theVideo.currentTime + 60);
            break;
        // 数字3-9对应keyCode 51-57,可按需添加逻辑
    }
};

实现YouTube同款百分比跳转

如果要和YouTube一致,按数字1跳转到视频10%位置、数字2跳转到20%…数字9跳转到90%,可以用以下代码:

var theVideo = document.getElementById("cspd_video");
document.onkeydown = function(event) {
    // 处理左右箭头逻辑
    if (event.keyCode === 37) {
        event.preventDefault();
        theVideo.currentTime = Math.max(0, theVideo.currentTime - 5);
        return;
    }
    if (event.keyCode === 39) {
        event.preventDefault();
        theVideo.currentTime = Math.min(theVideo.duration, theVideo.currentTime + 5);
        return;
    }

    // 处理主键盘数字键1-9(keyCode范围49-57)
    const keyCode = event.keyCode;
    if (keyCode >= 49 && keyCode <= 57) {
        event.preventDefault();
        // 计算目标百分比:数字1对应10%,数字2对应20%…
        const targetPercent = (keyCode - 48) * 10;
        theVideo.currentTime = (theVideo.duration * targetPercent) / 100;
    }
};

额外优化说明

  • 用Math.max(0, ...)避免视频时间跳转到负数
  • 用Math.min(theVideo.duration, ...)避免时间超出视频总时长
  • 若需支持小键盘数字键,可补充判断keyCode范围97-105(对应小键盘1-9)

内容的提问来源于stack exchange,提问作者yana

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 09:24:59