事件委托可以不给操作元素都绑定onmouse和onmouse事件;可以给所操作的元素加一个自定义属性;然后以自定义属性==自定义属性值来判断,就可以知道是否在当前页面上了;

 

HTML代码如下:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" href="css/xiaomi.css"/>
</head>
<body>
<div id="div1">
<ul>
<li >首页</li>
<li xiaomi="true">小米手机</li>
</ul>
<div id="div2" xiaomi="true"></div>
</div>



<h3 id="home_top">用事件委托实现小米手机导航 - Powered By <a href="http://taobao.fm/"target="_blank">broszhu</a>  博客网址:<a href="http://taobao.fm/" target="_blank">taobao.fm</a> </h2>
<p id="home_bottom">学习JavaScript是一件很有趣的事,可以做出很多自豪的小玩意!--broszhu (这个页面是实现原理:<a href="#" target="_blank">点此查看</a></p>
</body>
</html>
<script src="js/tools.min.js"></script>
<script src="js/xiaomi.js"></script>

CSS代码如下:

body,div,ul,li{
margin: 0;
padding: 0;
font-family: "\5FAE\8F6F\96C5\9ED1", Helvetica, sans-serif;
font-size: 16px;
-webkit-user-select:none;
}
ul,li{
list-style: none;
}
#div1{
width: 990px;
height: 250px;
margin: 146px auto 0;
}
#div1 ul{
width: 100%;
height: 50px;
line-height: 50px;

background: #3c3c3c;
}
#div1 ul li{
color: #FFF;
float: left;
padding: 0 10px;
cursor:pointer;
}
#div1 ul li:hover{
background: #101010;
}
#div2{
height: 0;
border:solid 1px #a9a9a9 ;
background: #F9AF2A;
border-top:0 ;
cursor: pointer;
}
#home_top {height: 48px;line-height:48px;font-size:18; text-align: center; color:#008CD7;}
#home_bottom {color:#008CD7;text-align:center;font-size:14px;}

javascript代码如下:

var tool = new Tool;
var oDiv2 = document.getElementById("div2");
document.onmouseover = function (e) {
e = e || window.event;//处理事件兼容性;
var tar = e.target || e.srcElement;//事件源;
var xiaomi = tar.getAttribute("xiaomi");//监听的对象;
var ch = tool.getCss("height", oDiv2);
if (xiaomi === "true") {//以属性来判断;
if (ch <= 200) {
move.call(oDiv2, 200)
}
} else {
if (ch > 0) {
move.call(oDiv2, 0)
}

}
};

function move(target) {
var that = this;
_move();
function _move() {
var start = tool.getCss("height", that);//要在内部,不能写在外面
clearTimeout(that.timer);
that.timer = setTimeout(_move, 10);
if (start >= target) {
tool.setCss(that, "height", start - 10);
if (start - 10 < target) {
tool.setCss(that, "height", target);
return;
}
} else if (start < target) {
tool.setCss(that,"height", start + 10);
if (start + 10 >= target) {
tool.setCss(that, "height", target);
return;
}
} else {
return;
}
}
}

··················