来看看效果图:
封装好的运动函数move.js就是“javascript运动基础——摩擦和缓冲”中封装的函数
这是源代码
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<script type="text/javascript" src="js/move.js"></script>
<style>
#ul {
width: 300px;
height: 300px;
position: relative;
display: block;
margin: 0 auto;
}
li {
list-style: none;
width: 90px;
height: 90px;
margin: 10px 0 0 10px;
background-color: yellow;
float: left;
}
</style>
</head>
<body>
<ul id="ul">
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<script>
window.onload = function() {
var oUl = document.getElementById('ul');
var oLi = document.getElementsByTagName('li');
var arr = [];
for(var i = 0; i < oLi.length; i++) {
oLi[i].index = i;
//提前保存好元素最开始的位置
arr.push({
left: oLi[i].offsetLeft,
top: oLi[i].offsetTop
})
}
for(var i = 0; i < oLi.length; i++) {
//定位后浮动效果就是失效了
oLi[i].style.position = 'absolute';
//重新设置li的位置
oLi[i].style.left = arr[i].left + 'px';
oLi[i].style.top = arr[i].top + 'px';
//因为元素保存后的位置就是偏移后的,所以要把外边距清除掉
oLi[i].style.margin = 0;
oLi[i].onmouseover = function() {
startMove(this, {
width: 150,
height: 150,
left: arr[this.index].left - 40,
top: arr[this.index].top - 40
});
}
oLi[i].onmouseout = function() {
startMove(this, {
width: 90,
height: 90,
left: arr[this.index].left,
top: arr[this.index].top
});
}
}
}
</script>
</body>
</html>