案例1 电量小灯泡 主要内容:获取button对象,和.onclick事件的出发
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>点灯开关</title>
<img id="lightoff" src="../img/off.gif">
<script>
function f() {
/*判断当前light的状态*/
if (flag) {/*flag=true代表灯亮*/
light.src = "../img/off.gif"
flag=false;
}else{
light.src = "../img/on.gif"
flag=true;
}
}
var flag=false;
var light=document.getElementById("lightoff");
light.onclick=f;
</script>
</head>
<body>
</body>
</html>
案例2 打开网址,主要内容:open .close
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>打开关闭</title>
</head>
<body>
<input type="button" id="openbutton" value="打开">
<input type="button" id="closebutton" value="关闭">
<script>
var openbut=document.getElementById("openbutton");
var closebut=document.getElementById("closebutton");
var newWindow;
openbut.onclick=function () {
newWindow=open("www.baidu.com");
}
closebut.onclick=function () {
newWindow.close();
}
</script>
</body>
</html>
案例3 轮播图 主要内容 倒计时 setInterval(f,2000);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>轮播图</title>
<img src="../img/banner_1.jpg" id="banner" width="100%">
</head>
<body>
<script>
var img = document.getElementById("banner");
var num = 1;
function f() {
if (num <=3) {
img.src = "../img/banner_" + num + ".jpg";
num++;
} else {
num = 1
}
}
setInterval(f,2000);
</script>
</body>
</html>
案例4 页面自动跳转
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>自动跳转页面</title>
<style>
p{text-align: center}
span{color: crimson}
</style>
</head>
<body>
<p>
<span id="time">5</span> 秒后自动跳转到主页
</p>
<script>
var time=5;
var second = document.getElementById("time");
function timeCount() {
if (time==0) {
location.href = "http://www.baidu.com"
} else {
time--;
second.innerHTML = time + "";/*获取到的对象的内容=倒计时time*/
}
}
setInterval(timeCount,1000);
</script>
</body>
</html>