Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
487 views
in Technique[技术] by (71.8m points)

js可以模拟ESC键盘事件吗?

我说的不是Keycode
不是按下键盘上的ESC.
就是单击一个效果然后模拟下ESC就退出全屏播放的效果。


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

本来可以用KeyboardEvent来实现的,但是这个浏览器的兼容性很差,有坑。

下面推荐一种自定义事件的方式来模拟,我是用document来监听事件的,可以换成你想要的DOM元素:

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <button onclick="testEvent()">点我</button>

    <script>
        document.addEventListener('testEsc', function(e) {
            //此处填写你的业务逻辑即可
            console.log('模拟esc事件')
        })

        function testEvent() {
            //自定义事件 testEsc
            var event = new CustomEvent('testEsc', {
                ctrlKey: false,
                shiftKey: false,
                altKey: false
            });
            //触发事件
            document.dispatchEvent(event);
        }
    </script>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

[4] html - How to create even cell spacing within a

2.1m questions

2.1m answers

60 comments

57.0k users

...