如何通过按键盘上的“输入”按钮或其他按钮的组合来触发鼠标单击页面上的某个元素?
答案 0 :(得分:2)
尝试以下代码:
<!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>
答案 1 :(得分:1)
我用香草JS弄清楚了
window.onkeyup = function(e) {
var key = e.keyCode
if (key == 13) {
document.getElementById('test').click()
}
}
这将监视有人按下按钮的时间,然后检查他们是否按下Enter键, 如果他们这样做了,它将对ID为'test'的元素进行一次点击
答案 2 :(得分:0)
simulate(document.getElementById("btn"), "click");