你可以使用以下的 Vanilla JavaScript 代码来实现点击事件监听器,从而在红色和蓝色之间切换背景颜色:
<!DOCTYPE html>
<html>
<body>
<button onclick="toggleColor()">点击我</button>
<script>
function toggleColor() {
var body = document.body;
body.style.backgroundColor = body.style.backgroundColor ==='red'? 'blue' :'red';
}
</script>
</body>
</html>
在上述代码中,我们首先获取了文档的 body 元素,并将其存储在变量 body
中。然后,我们定义了一个名为 toggleColor
的函数,该函数在被点击时会被调用。
在 toggleColor
函数中,我们使用 body.style.backgroundColor
获取当前的背景颜色,并将其与 'red'
进行比较。如果当前颜色是红色,我们将其设置为蓝色;否则,我们将其设置为红色。
最后,我们将 toggleColor
函数作为点击事件监听器添加到按钮上,当按钮被点击时,toggleColor
函数会被调用,从而实现背景颜色的切换。
希望这个示例对你有帮助。如果你有任何其他问题,请随时提问。