今天在项目中遇到了个问题,在用js操作禁用按钮的时候没有生效,写了个demo演示一下,意思就是让某个按钮点击之后让另一个按钮的事件失效。代码如下:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 200px;
height: 200px;
background-color: red;
}
</style>
</head>
<body>
<div class="box"></div>
<button class="b1">点击切换</button>
<button class="b2">点击停止</button>
<script>
let box = document.querySelector('.box')
let b1 = document.querySelector('.b1')
let b2 = document.querySelector('.b2')
function qh() {
let r = Math.floor(Math.random() * 256)
let g = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
box.style.background = `rgb(${r},${g},${b})`
}
b1.addEventListener('click', qh)
b2.addEventListener('click', function () {
// b1.removeEventListener('click', qh)
b1.style.disabled = true
})
</script>
</body>
</html>
解决方法:b1.setAttribute('disabled', 'disabled') 或者 b1.disabled = true