了解了运动框架完成块元素的宽高和透明度的变化的原理,我想着写一个颜色的变化来练习一下,不想写了很长时间才写出来,跟各位分享一下。
颜色的变化是通过三元素渐变的方式完成的,通过构造json,使当前的颜色与目标颜色进行对比,实现渐变的过程。
代码如下:
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <style> 7 div{ 8 display: inline-block; 9 width: 50px; 10 height: 50px; 11 background: rgb(220,254,235); 12 position: absolute; 13 top: 100px; 14 } 15 </style> 16 </head> 17 <body> 18 <div style="left: 100px"></div> 19 </body> 20 </html> 21 <script> 22 //获取元素样式,并设置 23 function getStyle(obj,attr,value){ 24 if(arguments.length == 2){ 25 if(obj.currentStyle){ 26 return obj.currentStyle[attr]; 27 }else{ 28 return getComputedStyle(obj,false)[attr]; 29 } 30 }else if(arguments.length == 3){ 31 obj.style[attr] = value; 32 } 33 } 38 //运动框架 透明度 + 颜色 + 基本 39 function move(obj,json,fn){ 40 clearInterval(obj.timer); 41 42 obj.timer = setInterval(function(){ 43 var bStop = true; 44 for(var name in json){ 45 var iCur = 0; 46 47 if(name == "opacity"){ //若name为opacity时 48 iCur = parseInt(parseFloat(getStyle(obj,name))*100); 49 var iSpeed = (json[name]*100 - iCur)/10; 50 iSpeed = iSpeed>0 ? Math.ceil(iSpeed) : Math.floor(iSpeed); 51 obj.style.opacity = (iCur + iSpeed)/100; 52 obj.style.filter = "alpha(opacity:" + iCur + iSpeed +")"; 53 }else if(name == "background"){ //若name为background时(该部分代码完全自己所想,不代表标准模式,望有更好意见的访客能给出更好的意见) 54 //获取颜色的三元素 str = rgb(r,g,b) 55 function getColor(str){ //获取到背景色的三元素,进行拆分 56 var s = str.substring(4,str.length-1); 57 var arr = s.split(","); 58 var r = parseInt(arr[0]); 59 var g = parseInt(arr[1]); 60 var b = parseInt(arr[2]); 61 return { 62 red : r, 63 green : g, 64 blue : b 65 }; 66 } 67 68 iCur = getStyle(obj,"background-color"); //当前背景色 69 var newStr = json[name]; 70 var arr = []; //定义一个数组,用来存放新的三元素的值 71 var newJson = {}; //将设置的背景色写成一个json,并与getColor相对应 72 newJson.red = getColor(newStr).red; 73 newJson.green = getColor(newStr).green; 74 newJson.blue = getColor(newStr).blue; 75 76 for(var name in newJson){ //newJson中循环,得到最新的三元素 77 var cur = parseInt(getColor(iCur)[name]); 78 var iSpeed = (newJson[name] - cur)/10; 79 iSpeed = iSpeed>0 ? Math.ceil(iSpeed) : Math.floor(iSpeed); 80 var tmp = cur + iSpeed; 81 arr.push(tmp); 82 } 83 obj.style.background = "rgb(" + arr[0] + ","+ arr[1] + ","+ arr[2] + ")"; 84 }else{ //name为width height 85 iCur = parseInt(getStyle(obj,name)); 86 var iSpeed = (json[name] - iCur)/10; 87 iSpeed = iSpeed>0 ? Math.ceil(iSpeed) : Math.floor(iSpeed); 88 obj.style[name] = iCur + iSpeed + "px"; 89 } 90 if(iCur != json[name]) bStop = false; 91 } 92 if(bStop){ 93 clearInterval(obj.timer); 94 if(fn) fn(); 95 } 96 },30) 97 } 98 99 window.onload = function(){ 100 var oDiv = document.getElementsByTagName("div")[0]; 101 102 oDiv.onmouseover = function(){ 103 move(oDiv,{width:200,height:300,opacity:0.5,background:"rgb("+234+","+" "+ 124+","+" "+ 211+")"}); 104 } 105 } 106 </script>
时间: 2024-10-12 23:15:16