- div{
- width: 300px;
- height: 50px;
- background-color: red;
- color: white;
- }
- <body>
- <div>
- 这个DIV可以点击 <br>
- 点击时会触发一个键盘事件
- </div>
- <script>
- var div = document.querySelector('div')
- div.addEventListener('click',function(e){
- var keyEvent =new KeyboardEvent('keydown',{
- key:'p',
- code:'KeyP',
- ctrlKey:true,
- keyCode:0,
- charCode:112
- })
- window.dispatchEvent(keyEvent)
- })
- window.onkeydown =function(e){
- alert('键盘事件' + e.charCode + '|' + e.code)
- alert(e.ctrlKey?'ctrl被按下':'ctrl没有被按下')
- }
- // 模拟键盘事件 不会触发浏览器自身的快捷键 如 Ctrl + p
- </script>
- </body>