用js实现多个目标移动,当鼠标移上去的时候改变宽度,鼠标移出去的时候变回原来宽度。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> 让多个目标移动 </title>
<style>
body{
margin: 0;
padding: 0;
}
ul,li{
list-style: none;
}
ul li{
200px;
height: 100px;
background: orange;
margin-bottom: 20px;
border: 4px solid black;
}
</style>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</body>
<script>
var aLi = document.getElementsByTagName('li');
for(var i = 0; i < aLi.length; i++){
aLi[i].timer = null;
aLi[i].addEventListener('mouseover', function () {
startMove(this,400); //宽变成400(该宽包含了border)
});
aLi[i].addEventListener('mouseout', function () {
startMove(this,200);
});
}
function startMove(obj,iTarget){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var speed = (iTarget-parseInt(getStyle(obj,'width')))/8;
speed = speed > 0? Math.ceil(speed):Math.floor(speed);
if(obj.offsetWidth == iTarget){
clearInterval(obj.timer);
} else {
obj.style.width = parseInt(getStyle(obj,'width')) + speed + 'px';
}
},30); // 每30毫秒
}
//获取样式
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj,false)[attr];
}
}
</script>
</html>