<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
ul{list-style: none}
*{margin:0; padding:0;}
div{
height: 400px;
margin:50px auto;
border:1px solid red;
background:pink;
width:1150px;
overflow:hidden;
}
div li {
width: 240px;
height: 400px;
float:left;
}
div ul {
width: 1200px;
}
</style>
</head>
<body>
<div id="odiv">
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</div>
</body>
</html>
<script src="sport2.js"></script>
<script type="text/javascript">
var lis = document.getElementsByTagName("li");
for(var i=0; i<lis.length; i++) {
lis[i].style.backgroundImage = "url(images/"+(i+1)+".jpg)";
lis[i].onmouseover = function() {
for(var j=0; j<lis.length; j++) {
startMove(lis[j],100,"width");
}
startMove(this,800,"width");
}
lis[i].onmouseout = function() {
// 所有li全部变为默认宽度
for(var j=0; j<lis.length; j++) {
startMove(lis[j],240,"width");
}
}
}
</script>
sport2.js
/**
*
* @param obj 运动的元素
* @param target 目标值
* @param attr 操作属性
* @param callback 回调函数
*/
function startMove(obj,target,attr,callback) {
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var current = parseFloat(getStyle(obj,attr));
var speed = 0;
if (attr === "opacity") {
speed = target - current > 0 ? 0.1: -0.1;
} else {
speed = (target - current)/10; //
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
}
//
if (current === target) {
clearInterval(obj.timer);
// 上一个动作执行完 进入下一个动作
if (callback) {
callback();
}
} else {
if (attr === "opacity") {
obj.style[attr] = current + speed
} else {
obj.style[attr] = current + speed + "px";
}
}
},20);
}
function getStyle(obj,attr) {
if (window.getComputedStyle) {
return window.getComputedStyle(obj,false)[attr];
} else {
return obj.currentStyle[attr];
}
}
效果图