js运动
匀速运动
function stratMove(dom, target){
var timer = null;
clearInterval(timer);
var iSpeed = target - dom.offsetLeft > 0 ? 7 : -7;
dom.timer = setInterval(function(){
if(Math.abs(target - dom.offsetLeft) < Math.abs(iSpeed)) {
clearInterval(dom.timer);
dom.style.left = target + 'px';
}else{
dom.style.left = dom.offsetLeft + iSpeed + 'px';
}
},30)
}
缓冲运动
function startMove(dom, target){
var dom.timer = null;
clearInterval(timer);
var iSpeed = null;
dom.timer = setInterval(function(){
iSpeed = (target - odiv.offsetLeft) / 7;
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
if(dom.offsetLeft == target){
clearInterval(dom.timer)
}else{
dom.style.left = dom.offsetLeft + iSpeed +'px';
}
},30)
}
获取属性样式
function getStyle (don, attr){
if(window.getComputedStyle){
return window.getComputedStyle(dom, null)[attr];
}else{
return dom.currentStyle[attr];
}
}
透明度
function startMove(dom, target){
clearInterval(timer);
var iSpeed = null, iCur = null;
dom.timer = setInterval(function (){
iCur = parseFloat( getStyle(dom, 'opacity') ) * 100;
iSpeed = (target - iCur) / 7;
console.log(iSpeed)
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
if ( iCur == target){
clearInterval(dom.timer)
}else{
dom.style.opacity = (iCur + iSpeed) / 100;
}
},30)
}
多物体值运动
function startMove(dom, attr, target){
clearInterval(dom.timer);
var iSpeed = null, iCur = null;
dom.timer = setInterval(function (){
if (attr == 'opacity'){
iCur = parseFloat(getStyle(dom, attr) ) * 100
}else{
iCur = parseFloat(getStyle(dom, attr));
}
iSpeed = (target - iCur) / 7;
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
if (iCur == target) {
clearInterval(dom.timer);
}
if( attr == 'opacity'){
dom.style.opacity = (iCur + iSpeed) / 100;
}else{
dom.style[attr] = iCur + iSpeed + 'px'
}
}, 30)
}
多物体多值 + 回调函数
function startMove(dom, attrObj, callback) {
清除定时器,元素的定时器
clearInterval(dom.timer);
var iSpeed = null, iCur = null;
定时器
dom.timer = setInterval(function () {
var bStop = true;
for (var attr in attrObj) {
if (attr == 'opacity') {
iCur = parseFloat(getStyle(dom, attr)) * 100
} else {
iCur = parseFloat(getStyle(dom, attr));
}
iSpeed = (attrObj[attr] - iCur) / 7;
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
if(attr == 'opacity'){
dom.style.opacity = (iCur + iSpeed) / 100;
}else{
dom.style[attr] = iCur + iSpeed + 'px'
}
if( iCur != attrObj[attr]){
bStop = false;
}
}
if(bStop) {
clearInterval(dom.timer);
typeof callback == 'function' && callback()
}
}, 30)
}