所谓“运动”不一定真的是运动,在连续的一段时间内改变某一样式都可以成为“运动”。
先写几个会用到的函数
//获取某一元素的指定样式
function getstyle (element, target) {
// body...
if (element.currentStyle) {
return element.currentStyle[target];
}else{
return window.getComputedStyle(element, null)[target];
}
}
//填充digits长度的十六进制数
function zero_fill_hex(num, digits) {
var s = num.toString(16);
while (s.length < digits)
s = "0" + s;
return s;
} //rgb颜色转成十六进制颜色
function rgb2hex(rgb) { if (rgb.charAt(0) == '#')
return rgb; var ds = rgb.split(/\D+/);
var decimal = Number(ds[1]) * 65536 + Number(ds[2]) * 256 + Number(ds[3]);
return "#" + zero_fill_hex(decimal, 6);
}
最后是“运动”框架部分
/*
*在连续时间内改变某一样式(运动框架)
*@element 要改变样式的元素
*@target 要改变的样式
*@end 目标样式最终的值
*@speed 改变的速度
*@flag 是否变速改变,true为变速,false为匀速
*/
function changeStyle (element, target, end, speed, flag) {
// body...
if(target.indexOf("color") != -1){
var begin = $$.getStyle(element, target)+"";
begin = rgb2hex(begin).replace(/#/, '');
end = end.replace(/#/, '');
speed = Math.ceil(Math.abs(parseInt(begin, 16)-parseInt(end, 16))/speed); clearInterval(element[target+"Timer"]);
element[target+"Timer"] = setInterval(function(){
var intBegin = parseInt(begin, 16);
var intEnd = parseInt(end, 16);
speed = intEnd > intBegin ? Math.abs(speed) : (-Math.abs(speed)); if (Math.abs(intBegin-intEnd) <= Math.abs(speed)) {
clearInterval(element[target+"Timer"]);
element.style[target] = '#'+end;
}else {
var sum = intBegin + speed
begin = sum.toString(16);
element.style[target] = '#' + zero_fill_hex(begin, 6);
}
}, 30);
}
else if (target == "opacity") {
var begin = $$.getStyle(element, target)+"";
clearInterval(element[target+"Timer"]);
element[target+"Timer"] = setInterval(function(){
if (Math.abs(begin-end) <= Math.abs(speed)){
clearInterval(element[target+"Timer"]);
element.style.opacity = end;
}else{
begin = begin*1.0 + speed;
element.style.opacity = begin;
}
}, 30);
}else{
var begin = $$.getStyle(element, target)+"";
console.log("begin--- "+begin);
begin = begin.replace(/px/g, '');
clearInterval(element[target+"Timer"]);
element[target+"Timer"] = setInterval(function(){
var realSpeed = Math.abs(end-begin)/speed;
realSpeed = realSpeed > 0 ? Math.ceil(realSpeed) : Math.floor(realSpeed); if (Math.abs(begin-end) <= Math.abs(realSpeed)){
clearInterval(element[target+"Timer"]);
element.style[target] = end + "px";
}else{
if (flag)
begin = begin*1.0 + realSpeed;
else
begin = begin*1.0 + speed;
element.style[target] = begin + "px";
console.log(target+" "+begin+" "+realSpeed);
}
}, 30);
}
}