平时工作中写网页涉及的运动往往都非常简单,比如改变宽高,透明度,位置,是最常用的几种形式,为了省事,整合了下,于是就有了下面这个东东:
兼容:ie系列、chrome、firefox、opera、safari、360
/* javascript简易运动 move.action(dom对象,json格式属性值对,缓动参考值,回调方法) 示例: var box = document.getelementbyid('ele'); move.action(box,{width:500,height:200,left:200,top:100,marginleft:10,opacity:.5},5,function(){ console.log('end'); });*/var move = { version: '1.5', //判断是否空对象 isemptyobject: function(obj) { for (var attr in obj) { return false; } return true; }, //取css样式值 getstyle: function(obj, attr) { if (obj.currentstyle) { //ie return obj.currentstyle[attr]; } else { return getcomputedstyle(obj, null)[attr]; } }, //运动 action: function(obj, json, sv, callback) { _this = this; //obj是否为空 if (_this.isemptyobject(obj)) { return false; } //运动开始 clearinterval(obj.timer); obj.timer = setinterval(function() { var isallcompleted = true, //假设全部运动都完成了 speed, //速度 attrvalue, //当前值 targetv; //目标值 for (attr in json) { attrvalue = _this.getstyle(obj, attr); switch (attr) { case 'opacity': attrvalue = math.round((isnan(parsefloat(attrvalue)) ? 1 : parsefloat(attrvalue)) * 100); speed = (json[attr] * 100 - attrvalue) / (sv || 4); targetv = json[attr] * 100; break; default: attrvalue = isnan(parseint(attrvalue)) ? 0 : parseint(attrvalue); speed = (json[attr] - attrvalue) / (sv || 4); targetv = json[attr]; } speed = speed > 0 ? math.ceil(speed) : math.floor(speed); //如果循环过程中存在尚未结束的运动,isallcompleted为假 if (attrvalue != targetv) { isallcompleted = false; } switch (attr) { case 'opacity': { obj.style.filter = alpha(opacity= + (attrvalue + speed) + ); obj.style.opacity = (attrvalue + speed) / 100; }; break; default: obj.style[attr] = attrvalue + speed + 'px'; } } //所有循环结束后,只有当全部运动结束后(isallcompleted=true)时才关闭定时器 if (isallcompleted) { clearinterval(obj.timer); if (typeof callback === 'function') { callback(); } } }, 30); }};
以上就是描述了javascript实现网页中涉及的简易运动的方法,希望对大家实现javascript简易运动有所启发。