1,获取按钮对象;
2,绑定事件:这里l两种方式:一种绑定图片,另一种绑定按钮开关;
3,定义一个标记变量,与图片的状态同步,这里是最重要的.
<!DOCTYPE html>
<html lang="en">
<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>
</head>
<body><img src="../资源/img/off.gif" alt=""><button id="btn">开关</button><script>//1,获取按钮对象var btn = document.querySelector('#btn')var img = document.querySelector('img')//定义一个标记变量,与图片的状态同步var flag = false//false代表灯泡是灭的//2,绑定事件//点击按钮变色btn.onclick = function(){if(flag == false){img.src = '../资源/img/on.gif'flag = true//将flag的状态更新,亮}else{img.src = '../资源/img/off.gif'flag = false//将flag的状态更新,灭}}var btn = document.getElementById('#bookname')btn.onclick = function(){alert(btn)}//点击图片变色img.onclick = function(){if(flag == false){img.src = '../资源/img/on.gif'flag = true//将flag的状态更新,亮}else{img.src = '../资源/img/off.gif'flag = false//将flag的状态更新,灭} }</script>
</body>
</html>