我如何隐藏我的自定义html5视频控件时,用户是不活跃的

How can I hide my custom html5 video controls when the user is inactive?

本文关键字:控件 用户 活跃 视频 html5 何隐藏 隐藏 自定义 我的      更新时间:2023-09-26

我有一些自定义html5视频控件,我想在用户观看视频时隐藏它们。我将等待两秒钟,如果他们没有移动鼠标,我将隐藏控件,然后当他们再次移动鼠标时,我将显示控件。

有什么切实可行的方法来做到这一点?

mousemove事件与setTimeout一起使用

mouse移动清除setTimeout

var elem = document.getElementById('controls');
var timeout;
var duration = 3000;
document.addEventListener('mousemove', function() {
  elem.textContent = 'Mouse is moving!'
  clearTimeout(timeout);
  timeout = setTimeout(function() {
    elem.textContent = 'Mouse Has stopped!'
  }, duration)
});
<div id="controls">Mouse Has stopped!</div>

<

小提琴演示/h2>

使用controls属性

var video = document.getElementById('videoElem');
var timeout;
var duration = 500;
document.addEventListener('mousemove', function() {
  video.setAttribute("controls", "controls");
  clearTimeout(timeout);
  timeout = setTimeout(function() {
    video.removeAttribute("controls");
  }, duration)
});
html {
  padding: 20px 0;
  background-color: #efefef;
}
body {
  width: 400px;
  padding: 40px;
  margin: 0 auto;
  background: #fff;
  box-shadow: 1px 1px 5px rgba(0, 0, 0, 0.5);
}
video {
  width: 400px;
  display: block;
}
<video preload controls id="videoElem">
  <source id="mp4" src="http://grochtdreis.de/fuer-jsfiddle/video/sintel_trailer-480.mp4" type="video/mp4">
</video>

<

小提琴演示/h2>

我最终使用了timeupdate事件:

var counts = 0
function hideOnIdle (video) {
  if (video.paused === true) return controls.classList.remove('hidden')
  if (counts > 7) {
    controls.classList.add('hidden')
    counts = 0
  }
  counts += 1
}
document.addEventListener('mousemove', function (event) {
  controls.classList.remove('hidden')
  counts = 0
}, false)