本文实例为大家分享了js实现电灯开关效果的具体代码,供大家参考,具体内容如下
通过对js的一个学习,我们来完成一个模拟电灯开关的小案例。
首先对本案例进行一个分析,过程如下:
1.获取图片属性
2.绑定单击事件
3.点击时切换图片
1.通过按钮实现电灯开关
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< title >Title</ title >
</ head >
< body >
< img src = "imgs/on.gif" alt = "" id = "img" > < br > <!--图片-->
< input type = "button" id = "bt1" value = "开" onclick = "f1()" > <!--按钮-->
< button id = "bt2" onclick = "f2()" >关</ button >
</ body >
< script >
function f1() {//开
let bt1=document.getElementById("bt1");//获取按钮id
let img=document.getElementById("img");//获取图片id
img.src="imgs/on.gif";//修改图片
}
function f2() {//关
let bt2=document.getElementById("bt2");
let img=document.getElementById("img");
img.src="imgs/off.gif";
}
</ script >
</ html >
|
运行结果:
2.通过点击电灯,实现开关
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< title >Title</ title >
</ head >
< body >
< img src = "imgs/off.gif" alt = "" id = "img" > < br >
</ body >
< script >
let img=document.getElementById("img");
img.onclick=f;
let flag=false;
function f() {
if (flag==true){
img.src="imgs/off.gif"
flag=false;
}else {
img.src="imgs/on.gif"
flag=true;
}
}
</ script >
</ html >
|
简化版(利用三元运算符)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
<!DOCTYPE html>
< html lang = "en" >
< head >
< meta charset = "UTF-8" >
< title >Title</ title >
</ head >
< body >
< img src = "imgs/on.gif" height = "180" width = "109" id = "img" onclick = "f()" >
</ body >
< script >
let img = document.getElementById("img");
let i=0;
function f() {
img.src='imgs/'+(++i%2==0?'off':'on')+'.gif';
}
</ script >
</ html >
|
运行结果
通过点击实现电灯的开关
电灯素材:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/qq_45850095/article/details/112709631