jQuery制作随机变色
大家都知道,我们可以通过:hover来改变元素悬停状态下的相关参数,特别是元素的色彩,但:hover在现代浏览器上实现是没有问题,可在IE6下就只能适用在<a>元素上,其他元素就无法正常显示(具体可以看《浏览器兼容之旅的第四站:IE常见Bug——part2》)。但是我们可以通过jQuery来实现各个元素的相关属性改变。今天主要和大家一起来学习用jQuery随机改变元素的相关颜色,比如说:背景色,前景色,边框颜色等。
目标
我们今天主要来看一个实例——随机改变链接元素的前景色和背景色
HTML CODE
<ul id="nav"> <li><a href="">link</a></li> <li><a href="">link</a></li> <li><a href="">link</a></li> <li><a href="">link</a></li> <li><a href="">link</a></li> </ul>
CSS CODE
上面的结构是一个简单的列表,现在给其设置一个简单点的样式
*{padding: 0;margin: 0;}
#nav {
width: 15em;
margin: 0 auto;
}
#nav li {
list-style: none outside none;
height: 27px;
line-height: 27px;
}
#nav a {
display: block;
background: #f369d3;
color: #cde;
}
现在万事具备只欠东风了,我们接下来看最关键的一步,如何使用jQuery实现——随机改变链接元素的背景色和前景色。
要使用jQuery制作这样的效果,我们需要两样东西,其是就是jQuery的版本库,基二就是Color Animations插件。这两个东西大家可以从官网中下载:
大家也可以直接Copy下面的代码:
Color Animations插件以文件形式保存到您的电脑中
/*
* jQuery Color Animations
* Copyright 2007 John Resig
* Released under the MIT and GPL licenses.
*/
(function(jQuery){
// We override the animation for all of these color styles
jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
jQuery.fx.step[attr] = function(fx){
if ( fx.state == 0 ) {
fx.start = getColor( fx.elem, attr );
fx.end = getRGB( fx.end );
}
fx.elem.style[attr] = "rgb(" + [
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(",") + ")";
}
});
// Color Conversion functions from highlightFade
// By Blair Mitchelmore
// http://jquery.offput.ca/highlightFade/
// Parse strings looking for color tuples [255,255,255]
function getRGB(color) {
var result;
// Check if we're already dealing with an array of colors
if ( color && color.constructor == Array && color.length == 3 )
return color;
// Look for rgb(num,num,num)
if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];
// Look for rgb(num%,num%,num%)
if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];
// Look for #a0b1c2
if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];
// Look for #fff
if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];
// Otherwise, we're most likely dealing with a named color
return colors[jQuery.trim(color).toLowerCase()];
}
function getColor(elem, attr) {
var color;
do {
color = jQuery.curCSS(elem, attr);
// Keep going until we find an element that has color, or we hit the body
if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
break;
attr = "backgroundColor";
} while ( elem = elem.parentNode );
return getRGB(color);
};
// Some named colors to work with
// From Interface by Stefan Petre
// http://interface.eyecon.ro/
var colors = {
aqua:[0,255,255],
azure:[240,255,255],
beige:[245,245,220],
black:[0,0,0],
blue:[0,0,255],
brown:[165,42,42],
cyan:[0,255,255],
darkblue:[0,0,139],
darkcyan:[0,139,139],
darkgrey:[169,169,169],
darkgreen:[0,100,0],
darkkhaki:[189,183,107],
darkmagenta:[139,0,139],
darkolivegreen:[85,107,47],
darkorange:[255,140,0],
darkorchid:[153,50,204],
darkred:[139,0,0],
darksalmon:[233,150,122],
darkviolet:[148,0,211],
fuchsia:[255,0,255],
gold:[255,215,0],
green:[0,128,0],
indigo:[75,0,130],
khaki:[240,230,140],
lightblue:[173,216,230],
lightcyan:[224,255,255],
lightgreen:[144,238,144],
lightgrey:[211,211,211],
lightpink:[255,182,193],
lightyellow:[255,255,224],
lime:[0,255,0],
magenta:[255,0,255],
maroon:[128,0,0],
navy:[0,0,128],
olive:[128,128,0],
orange:[255,165,0],
pink:[255,192,203],
purple:[128,0,128],
violet:[128,0,128],
red:[255,0,0],
silver:[192,192,192],
white:[255,255,255],
yellow:[255,255,0]
};
})(jQuery);
jQuery版本库和Color Animations插件都备好后,我们只需要将他们导入到你的项目中:
<script type="text/javascript" src="js/jquery.min.js"></script> <script type="text/javascript" src="js/jquery.color.js"></script>
接下来就是写jQuery代码,让相关元素实现随机变色的效果。
jQuery Code
$(document).ready(function(){
//获取a元素的默认前景色和背景色
var $color = $("#nav a").css("color");
var $backgroundColor = $("#nav a").css("background-color");
//给a元素添加.hover事件
$("#nav a").hover(function(){//鼠标在链接上的效果,也就是mouseover状态
//定义动态的前景色和背景色
var col = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
var backgroundColor = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
//通过.animate()方法动态改元素元素的相关CSS样式
$(this).stop().animate({
"color": col,
"background-color": backgroundColor,
"padding-left":"20px",
"margin-left":"10px"
},1000);
},function(){//鼠标移出链接,相当于mouseout状态
$(this).stop().animate({
"color": $color,//a元素的默认前景色
"background-color": $backgroundColor,//a元素的默认背景色
"padding-left":"0px",
"margin-left":"0"
},500);
});
});
到此我们就轻松制作出随机改变a元素的前景色和背景色。这种效果并不适合每一个人,只提供相关思路以供参考。有时或许能用得上。
最后规纳一下:上面主要介绍的是如何随机改变a元素的背景和前景色,实现此功能,我们主要使用了jQuery方法,配合Color Animations插件。其中还运用了jQuery中的.hover()、.stop()以及.animate()方法。当然大家还可以使用.mouseover()和.mouseout()方法来代替.hover()。
注:上面为何在.animate()前使用.stop()?至于具体答案可以点击Brandon Aaron写的《Quick Tip: Prevent Animation Queue Buildup》一文,Brandon Aaron在此文中解释的很清楚。大家要是感兴趣可以阅读一下。
如需转载烦请注明出处:W3CPLUS



