H5视频禁止快进 & 播放完退出全屏

551 阅读1分钟

禁止快进

通过监听 timeupdate 事件实现禁止用户拖拽进度条快进,代码如下:

const video = document.querySelector('video')

let lastCureentTime = 0
video.addEventListener('timeupdate', () => {
    const current = video.currentTime
    if (current - lastCureentTime > 2) {
      video.currentTime = lastCureentTime
    } else {
      lastCureentTime = current
    }
})

播放完退出全屏

通过监听 video 标签的 ended 事件,在视频播放结束时,将全屏播放的视频,通过 Fullscreen API 退出全屏显示,代码如下:

const video = document.querySelector('video')

video.addEventListener('ended', () => {
    const fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement
    if (fullscreenElement === video) {
      const exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen
      exitFullscreen && exitFullscreen.call(document)
      console.log('退出')
    }
})

在IOS端时,点击视频播放时会默认自动全屏,可以给 video 标签添加 playsinline 、webkit-playsinline 这两个属性解决