我也是跟着老师的写的,除了json不行外,链式和其他都行,麻烦大佬帮忙看一下
move.js:
//获取样式,浏览器兼容
function getStyle(obj, attr) {
if(obj.currentStyle) {
return obj.currentStyle[attr]; }else {
return getComputedStyle(obj,false)[attr];
}
}
function startMove(obj, json, cb) {
//定时器,方便清空
//var obj.timer = null;
//打开定时器之前,先清空,避免定时器重复开启
clearInterval(obj.timer);
obj.timer = setInterval(function() {
for(var attr in json) {
//1.取当前值
var icur = 0;
//透明度不需要最后加'px',所以跟尺寸分情况讨论
if(attr == 'opacity') {
//透明度非整数,且为了避免精度显示问题
icur = Math.round(parseFloat(getStyle(obj, attr))*100);
//console.log('opacity:', icur);
}else {
icur = Math.round(parseFloat(getStyle(obj, attr)));
//icur = Math.round(Number(getStyle(obj, attr)));
//console.log('getStyle:', getStyle(obj, attr));
//console.log('icur:', icur);
}
//2.算速度
var speed = (json[attr] - icur)/8;
//向绝对值大的方向取整
speed = speed>0 ? Math.ceil(speed) : Math.floor(speed);
//console.log('speed:', speed);
//3.到达目标值,停止
if(icur == json[attr]) {
clearInterval(obj.timer);
if(cb) {
//如果有回调函数,则执行
cb();
}
}else {
if(attr == 'opacity') {
//IE和firefox的兼容性问题
obj.style.filter = 'alpha:(opacity:'+icur + speed+')';
obj.style.opacity = (icur+speed)/100;
//console.log('一次运动后:', obj.style.opacity);
}else {
obj.style[attr] = icur + speed + 'px';
//console.log('一次运动后:', obj.style[attr]);
}
}
}
}, 30);
}
下面是jsonMove.html:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
* {
margin: 0;
padding: 0;
}
#div1 {
width: 200px;
height: 200px;
background: red;
}
</style>
</head>
<body>
<div id="div1"></div>
<script src="js/move.js"></script>
<script>
window.onload = function() {
var oDiv = document.getElementById('div1');
oDiv.onmouseover = function() {
var json1 = {width:400, height:200};
startMove(oDiv, json1);
}
}
</script>
</body>
</html>