按钮focus(点击按钮后,键盘的空格键和enter键会再次触发按钮点击事件)
一、问题描述
当我们在浏览器点击按钮之后,再次按键盘的空格键或者enter键均会再次触发此按钮的点击事件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="test()">测试</button>
<script>
function test() {
const P = document.createElement('p')
P.innerHTML = '按钮被点击了'
document.querySelector('body').appendChild(P)
}
</script>
</body>
</html>
我们可以创建一个html,输入上面的代码,在浏览器打开之后,自行尝试
我们只要点击按钮一次之后,按enter键或者空格键,按钮的点击事件就会一直被触发。除非我们鼠标点击其他地方。
这是因为按钮被浏览器选中(focus)了。
二、解决方式
有些时候我们不希望这种情况出现,这里有两种解决方式
1.替换标签
使用div、span、p这类标签来替代button和input按钮
当然,这种建议在项目一开始时就想到这种情况,不然后续可能要花较多时间去修改样式
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
.btn {
width: 100px;
height: 40px;
background-color: greenyellow;
border: 1px solid #000;
text-align: center;
line-height: 40px;
box-sizing: border-box;
cursor: pointer;
}
</style>
</head>
<body>
<!--<button οnclick="test()">测试</button>-->
<div class="btn" onclick="test()">测试</div>
<script>
function test() {
const P = document.createElement('p')
P.innerHTML = '按钮被点击了'
document.querySelector('body').appendChild(P)
}
</script>
</body>
</html>
2.阻止键盘的默认事件
这种就比较直接点,阻止键盘默认事件的触发
document.onkeyup = function (e) {
console.log(11);
if (e.code === 'Space' || e.code === 'Enter') {
e.preventDefault()
}
}
判断若是空格键或者enter键时,不去触发默认事件即可
完整代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<button onclick="test()">测试</button>
<script>
function test() {
const P = document.createElement('p')
P.innerHTML = '按钮被点击了'
document.querySelector('body').appendChild(P)
}
document.onkeyup = function (e) {
console.log(11);
if (e.code === 'Space' || e.code === 'Enter') {
e.preventDefault()
}
}
</script>
</body>
</html>