js监听Enter回车键事件,例如网页上回车提交表单
一、全局监听keydown
或 keyup
事件:
document.addEventListener('keydown', function(event) {
if (event.key === 'Enter' || event.keyCode === 13) {
// 执行你的函数
yourFunction();
}
});
function yourFunction() {
console.log('回车键被按下!');
}
二、监听表单输入框的回车键(常用场景)
<input type="text" id="myInput" placeholder="按回车键执行">
<script>
const input = document.getElementById('myInput');
input.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault(); // 阻止表单默认提交行为(如果有)
yourFunction();
}
});
function yourFunction() {
console.log('输入框的回车键被按下,值:', input.value);
}
</script>
监听表单输入框回车提交案例:https://blog.nanzhi.vip/?article_id=2&type=idea
每天进步一点点