问题描述
我正在尝试设置一个 TamperMonkey
脚本,让键盘按键暂停原生 Chrome 视频播放器,而无需点击它或使用 Space Bar
为了实现这一点,我尝试设置一个脚本来触发 x,y coordinate
中的点击操作,其中视频显示在页面上。
到目前为止,它没有奏效。
// PAUSE VIDEO - ASSIGNED TO *Q* KEY
(function(){
document.addEventListener('keydown',function(e) {
if (e.keyCode == 81 && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.MetaKey) {
document.elementFromPoint(448,540).click(); // this should trigger the click on video to pause event
}
},false);
})();
谁能告诉我如何使用 Q
键暂停此视频?
解决方法
原生 HTMLVideoElement
在点击时不会播放/暂停,因此您需要使用 .play()
和 .pause()
方法,根据那个 .paused
只读布尔值。如果只有一个 .togglePlayback()
方法就好了,但没有。
(顺便说一句,using KeyboardEvent.keyCode
is depricated 支持 KeyboardEvent.key
。为了向后兼容,它仍然适用于主要网络浏览器,但它已在标准中正式弃用)
在 StackOverflow 上,请确保在单击蓝色按钮后单击代码片段(白框)内的任意位置。
(function () {
document.addEventListener('keydown',function (e) {
if (e.key == 'q' && !e.shiftKey && !e.ctrlKey && !e.altKey && !e.metaKey) {
const video = document.querySelector('video');
// or = document.elementFromPoint(448,540); if that's where it will always be
if (video.paused) video.play();
else video.pause();
}
},);
})();
<!-- Simple video example -->
<!-- 'Big Buck Bunny' licensed under CC 3.0 by the Blender foundation. Hosted by archive.org -->
<!-- Poster from peach.blender.org -->
<video controls
src="https://archive.org/download/BigBuckBunny_124/Content/big_buck_bunny_720p_surround.mp4"
poster="https://peach.blender.org/wp-content/uploads/title_anouncement.jpg?x11217"
width="300">
</video>