如何通过使用普通 JavaScript 按下键盘上的按钮来触发网页上某个元素上的 mouseclick 事件?
试试这个代码:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css" integrity="sha384-Smlep5jCw/wG7hdkwQ/Z5nLIefveQRIY9nfy6xoR1uRYBtpZgI6339F5dgvm/e9B" crossorigin="anonymous">
<title>Ilan's Test</title>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-lg-12" id="results">
</div>
</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js" integrity="sha384-o+RDsa0aLu++PJvFqy8fFScvbHFLtbvScb8AjopnFD+iEQ7wo/CG0xlczd+2O/em" crossorigin="anonymous"></script>
<script>
// We begin listening to keypresses on the document body
$(document).keypress(function(e) {
// If the key pressed was Enter (keycode 13)
if (e.keyCode == 13) {
// Perform an action -- You can now envoke a click event on an element's ID for example, here I just console log and append text to my results div
$('#results').append('<div>You hit enter!</div><hr>');
// Console log
console.log('you pressed enter');
return false;
}
});
</script>
</body>
</html>
我用 vanilla JS 解决了这个问题
window.onkeyup = function(e) {
var key = e.keyCode
if (key == 13) {
document.getElementById('test').click()
}
}
这将监视何时有人按下按钮,然后检查他们是否按下了 Enter, 如果他们这样做了,那么它将执行对 ID 为“test”的元素的点击
simulate(document.getElementById("btn"), "click");