问题描述
我在此网站上发现了许多结果,但它们似乎都使用了Jquery.我真的需要知道如何在没有Jquery的情况下进行操作.我想要的是单击一个按钮并触发例如ALT + N或CTRL + G的击键.谢谢.
I found many results for this on this website but they all seem to use Jquery. I really need to know how to do it without Jquery. What I want is to click a button and have the keystroke for example ALT+N or CTRL+G triggered. Thanks.
推荐答案
看看 KeyboardEvent
构造函数.您可以这样使用它:
Take a look at the KeyboardEvent
constructor. You could use it like this:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('alt-n').addEventListener('click', function () {
// create a new keyboard event
var event = new KeyboardEvent('keydown', {
key: 'n',
altKey: true
});
// dispatch the alt+n key press event
document.dispatchEvent(event);
});
document.getElementById('ctrl-g').addEventListener('click', function () {
// create a new keyboard event
var event = new KeyboardEvent('keydown', {
key: 'g',
ctrlKey: true
});
// dispatch the ctrl+g key press event
document.dispatchEvent(event);
});
// listen for any key presses
document.addEventListener('keydown', function (e) {
if (e.altKey || e.ctrlKey) {
// alt or ctrl is pressed
console.log('Key: ' + e.key + '; alt pressed: ' + e.altKey + '; ctrl pressed: ' + e.ctrlKey);
}
});
});
<button id="alt-n">alt+n</button>
<button id="ctrl-g">ctrl+g</button>
编辑
当浏览器解析您的HTML并到达<script>
标记时,它将立即在其中执行JavaScript.但是,可能会发生该文档的其余部分尚未加载的情况.
When the browser parses your HTML and reaches a <script>
tag, it immediately executes the JavaScript in it. It can however happen, that the rest of the document is not loaded yet.
这意味着页面中的某些HTML元素尚不存在,并且您无法在JavaScript中访问它们(document.getElementById
如果找不到该元素并且您可以返回null
,则可以返回null
从null
读取属性.
This means that some of the HTML elements in the page don't exist yet, and you can't access them in JavaScript (document.getElementById
will return null
if it can't find the element and you can't read properties from null
).
您必须等待,直到元素被加载.当然,您可以创建一个函数并在onclick
内联处理程序中调用它:
You have to wait until the elements are loaded. Of course, you could create a function and call it in an onclick
inline handler:
function dispatchAltN () {
var event = new KeyboardEvent('keydown', {
key: 'n',
altKey: true
});
document.dispatchEvent(event);
}
document.addEventListener('keydown', function (e) {
if (e.altKey || e.ctrlKey) {
// alt or ctrl is pressed
console.log('Key: ' + e.key + '; alt pressed: ' + e.altKey + '; ctrl pressed: ' + e.ctrlKey);
}
});
<button onclick="dispatchAltN();">alt+n</button>
但是,您不应使用内联JavaScript.
However, you should not use inline JavaScript.
幸运的是,浏览器在加载完页面内容后会触发一个事件.此事件称为DOMContentLoaded
.
Fortunately, the browser fires an event when it is done loading the contents of the page. This event is called DOMContentLoaded
.
在等待浏览器首次触发事件时,可以确保可以访问DOM中的所有元素.
When you wait for the browser to first fire the event, you can be sure that you can access all elements in the DOM.
这篇关于在没有Jquery的情况下单击鼠标即可触发Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!