<head>
<title>4-2多物体运动-获取样式各自运动</title>
<style type="text/css">
*
{
margin:0;
padding:0;
}
ul,li
{
list-style:none;
}
ul li
{
width:200px;
height:100px;
background:green;
margin-bottom:20px;
border:2px solid #000;
font-size:12px;
fliter:alpha(opacity:30);
opacity:0.3;
}
</style>
</head>
<body>
<ul>
<li id="li1"></li>
<li id="li2"></li>
<li id="li3">你是谁</li>
<li id="li4"></li>
</ul>
</body>
</html>
<script type="text/javascript">
//不同的目标 做不同的动画
window.onload = function () {
var aLi1 = document.getElementById('li1');
var aLi2 = document.getElementById('li2');
var aLi3 = document.getElementById('li3');
var aLi4 = document.getElementById('li4');
aLi1.onmousemove = function () {
statMove(aLi1, 'width', 400);
}
aLi1.onmouseout = function () {
statMove(aLi1, 'width', 200);
}
aLi2.onmousemove = function () {
statMove(aLi2, 'height', 200);
}
aLi2.onmouseout = function () {
statMove(aLi2, 'height', 100);
}
aLi3.onmousemove = function () {
statMove(this, 'font-size', 60);
}
aLi3.onmouseout = function () {
statMove(this, 'font-size', 12);
}
aLi4.onmousemove = function () {
statMove(this, 'opacity', 100);
}
aLi4.onmouseout = function () {
statMove(this, 'opacity', 30);
}
}
function statMove(obj,attr,iTarget) {
//方式一 :alert(getStyle(obj,'width')); 200px; obj.style.offsetWidth 则是 204px
clearInterval(obj.timer);
obj.timer = setInterval(function () {
var cul = 0;
if (attr == 'opacity') {//parseFloat小数点
cul = Math.round(parseFloat(getStyle(obj, attr))*100); //Math.round alert(0.7*100)=7.0000000000001需要做下处理 要不然透明度100.998
}
else {
cul = parseInt(getStyle(obj, attr));
}
speed = (iTarget - cul) / 8; //parseInt(getStyle(obj,'width'))转为数字
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (cul == iTarget) {
clearInterval(obj.timer);
}
else {
if (attr == 'opacity') {
obj.style.fliter = 'alpha(opacity:' + cul + speed + ')';
obj.style.opacity = (cul + speed) / 100;
}
//css样式高 透明度字体大小都可以改变
else {
obj.style[attr] = cul + speed + 'px'; //obj.style.width 可以写成 obj.style['width']
}
}
}, 30)
}
//方式二:去掉css的width,在行样式设置style="";
//方式三:获取样式 得到的是字符串 200px 宽 border包含在width里面
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr]; //获取样式 支持IE
}
else {
return getComputedStyle(obj, false)[attr]; //支持 火狐
}
}
</script>