2008/10/24

JQuery背景褪色解决方案,需插件Color Animations

背景褪色一般用于信息更改时提醒,一般使用的黄渐变(yellow fade )。

jquery1.2以后可以使用,但需要插件Color Animations ,首先下载插件,在页面中包含进来。

使用animate动画函数,设置backgroundColor属性即可,值形式可以为 rgb(num,num,num),rgb(num%,num%,num%),#a0b1c2
,#fff,。同时适用的属性还有:['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor']。

代码1:
 
<?php
$('.block').animate( { backgroundColor: 'pink' }, 1000)
    .animate( { backgroundColor: 'blue' }, 1000);
});
?>
 
代码2:
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
                    "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
  <script>
  $(document).ready(function(){
    $("#go").click(function(){
  $(".block").animate( { backgroundColor: 'pink' }, 1000)
    .animate( { backgroundColor: 'blue' }, 1000);
});
  });
  </script>
<style>
.block {
   background-color: blue;
   width: 150px;
   height: 70px;
   margin: 10px;
}
</style>
</head>
<body>
  <script src="http://dev.jquery.com/view/trunk/plugins/color/jquery.color.js"></script>
<button id="go">» Run</button>
<div class="block"></div>
</body>
</html>
 
简单说一下原理:
 
//将所有color的属性都设置一遍,以后在设置这些属性值时会调用下面定义的step函数
    jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
        jQuery.fx.step[attr] = function(fx){
            if ( fx.state == 0 ) {
                //取得当前的属性值,转为[255,255,255]的形式
                fx.start = getColor( fx.elem, attr );
                //取得设置的值,转为[255,255,255]的形式
                fx.end = getRGB( fx.end );
            }

            fx.elem.style[attr] = "rgb(" + [
                //用end-start的值乘以比率,在加上start的值,即得到每step的值。fx.pos为动画的完成比率
                Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
                Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
            ].join(",") + ")";
        }
    });
 

没有评论:

发表评论