初级案例:关闭京东广告栏
需求:点击x号,隐藏盒子。
思路:点击a链接,让top-banner这个盒子隐藏起来(加隐藏类名)。
步骤:
1.获取事件源和相关元素
2.绑定事件
3.书写事件驱动程序
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
* {
padding: 0;
margin: 0;
}
.top-banner {
background-color: pink;
height: 80px;
}
.w {
width: 1210px;
margin: 10px auto;
position: relative;
}
img {
width: 1210px;
height: 80px;
background-color: blue;
}
a {
position: absolute;
top: 5px;
right: 5px;
color: #fff;
background-color: #000;
text-decoration: none;
width: 20px;
height: 20px;
font: 700 14px/20px "simsum";
text-align: center;
}
.hide {
display: none!important;
}
</style>
</head>
<body>
<div class="top-banner" id="topBanner">
<div class="w">
<img src="" alt=""/>
<a href="#" id="closeBanner">×</a>
</div>
</div>
<script>
var closeBanner = document.getElementById("closeBanner");
var topBanner = document.getElementById("topBanner");
closeBanner.onclick = function () {
topBanner.className = "hide";
}
</script>
</body>
</html>
中级案例:京东狗的颜色变化
需求:鼠标放到img上,变化图片颜色(其实为修改图片地址值,转换为另一张图片)。
步骤:
1.获取事件源和相关元素
2.绑定事件
3.书写事件驱动程序
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<script>
window.onload = function () {
var img = document.getElementById("box");
img.onmouseover = function () {
img.src = "image/jd2.png";
this.src = "image/jd2.png";
}
var img = document.getElementById("box");
img.onmouseout = function () {
this.src = "image/jd1.png";
}
</script>
</head>
<body>
<img id="box" src="image/jd1.png" style="cursor: pointer;border: 1px solid #ccc;"/>
</body>
</html>