<!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>修改灯泡</title>
<style>
img{
width: 200px;
height: 300px;
}
</style>
</head>
<body>
<img src="../images/dark.jpg" alt="">
<button>开灯</button>
<script>
var img = document.getElementsByTagName('img')[0];
var btn = document.getElementsByTagName('button')[0];
var tag = true;
btn.onclick = function () {
if (tag) {
img.src = '../images/bright.jpg';
btn.innerText = '关灯';
} else {
img.src = '../images/dark.jpg';
btn.innerText = '开灯';
}
tag = !tag;
}
</script>
</body>
</html>
<!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>灯泡</title>
</head>
<body>
<div class="box">
<img src="../images/bark.jpg" alt="">
<button>开</button>
<button>关</button>
</div>
<script>
var box_img = document.getElementsByClassName('box')[0].getElementsByTagName("img")[0];
var box_btn = document.getElementsByClassName('box')[0].getElementsByTagName("button");
box_btn[0].onclick = function () {
box_img["src"] = "../images/light.jpg";
}
box_btn[1].onclick = function () {
box_img.src = "../images/bark.jpg";
}
</script>
</body>
</html>