了解了运动框架完成块元素的宽高和透明度的变化的原理,我想着写一个颜色的变化来练习一下,不想写了很长时间才写出来,跟各位分享一下。
颜色的变化是通过三元素渐变的方式完成的,通过构造json,使当前的颜色与目标颜色进行对比,实现渐变的过程。
代码如下:
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
div{
display: inline-block;
width: 50px;
height: 50px;
background: rgb(220,254,235);
position: absolute;
top: 100px;
}
</style>
</head>
<body>
<div style="left: 100px"></div>
</body>
</html>
<script>
//获取元素样式,并设置
function getStyle(obj,attr,value){
if(arguments.length == 2){
if(obj.currentStyle){
return obj.currentStyle[attr];
}else{
return getComputedStyle(obj,false)[attr];
}
}else if(arguments.length == 3){
obj.style[attr] = value;
}
}
//运动框架 透明度 + 颜色 + 基本
function move(obj,json,fn){
clearInterval(obj.timer); obj.timer = setInterval(function(){
var bStop = true;
for(var name in json){
var iCur = 0; if(name == "opacity"){ //若name为opacity时
iCur = parseInt(parseFloat(getStyle(obj,name))*100);
var iSpeed = (json[name]*100 - iCur)/10;
iSpeed = iSpeed>0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
obj.style.opacity = (iCur + iSpeed)/100;
obj.style.filter = "alpha(opacity:" + iCur + iSpeed +")";
}else if(name == "background"){ //若name为background时(该部分代码完全自己所想,不代表标准模式,望有更好意见的访客能给出更好的意见)
//获取颜色的三元素 str = rgb(r,g,b)
function getColor(str){ //获取到背景色的三元素,进行拆分
var s = str.substring(4,str.length-1);
var arr = s.split(",");
var r = parseInt(arr[0]);
var g = parseInt(arr[1]);
var b = parseInt(arr[2]);
return {
red : r,
green : g,
blue : b
};
} iCur = getStyle(obj,"background-color"); //当前背景色
var newStr = json[name];
var arr = []; //定义一个数组,用来存放新的三元素的值
var newJson = {}; //将设置的背景色写成一个json,并与getColor相对应
newJson.red = getColor(newStr).red;
newJson.green = getColor(newStr).green;
newJson.blue = getColor(newStr).blue; for(var name in newJson){ //newJson中循环,得到最新的三元素
var cur = parseInt(getColor(iCur)[name]);
var iSpeed = (newJson[name] - cur)/10;
iSpeed = iSpeed>0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
var tmp = cur + iSpeed;
arr.push(tmp);
}
obj.style.background = "rgb(" + arr[0] + ","+ arr[1] + ","+ arr[2] + ")";
}else{ //name为width height
iCur = parseInt(getStyle(obj,name));
var iSpeed = (json[name] - iCur)/10;
iSpeed = iSpeed>0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
obj.style[name] = iCur + iSpeed + "px";
}
if(iCur != json[name]) bStop = false;
}
if(bStop){
clearInterval(obj.timer);
if(fn) fn();
}
},30)
} window.onload = function(){
var oDiv = document.getElementsByTagName("div")[0]; oDiv.onmouseover = function(){
move(oDiv,{width:200,height:300,opacity:0.5,background:"rgb("+234+","+" "+ 124+","+" "+ 211+")"});
}
}
</script>