JavaScript–灯泡开关
这是点击后的效果(图片是自己P的,有点难看,不要见怪)
下面是代码展示:
<!DOCTYPE html>
<html><head><meta charset="utf-8"><title>灯泡开关</title><style>#div1{width: 500px;height: 500px;float: left;}#bulb1{width: 400px;height: 400px;}#div2{float: right;margin-right: 200px;}</style></head><body><div id="div1"><img src="img/bulb1.png" id="bulb1"/></div><div id="div2"></div><div><input type="button" value="开关" id="btn" onclick="getStr()"></div><script>var flag = true;function getStr(){var bulb = document.getElementById("bulb1");if(flag){bulb.src = "img/bulb2.png";document.getElementById("div2").innerHTML = date()+"灯开了";flag = false;}else{bulb.src = "img/bulb1.png";document.getElementById("div2").innerHTML = date()+"灯关了";flag = true;}}/*** 本地时间方法*/function date(){var strTime = new Date();var year = strTime.getFullYear();var month = strTime.getMonth()+1;var date = strTime.getDate();var hour = strTime.getHours();var minute = strTime.getMinutes();var miao = strTime.getSeconds();var time = year +"年"+month+"月"+date+"日"+hour+"时"+minute+"分"+miao+"秒";//必须由返回值,才能显示时间return time;}</script></body>
</html>