JS实现颜色梯度与渐变效果完整实例


Posted in Javascript onDecember 30, 2016

本文实例讲述了JS实现颜色梯度与渐变效果的方法。分享给大家供大家参考,具体如下:

运行效果图如下:

JS实现颜色梯度与渐变效果完整实例

完整实例代码如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JavaScript 颜色梯度和渐变效果</title>
<script type="text/javascript">
var $ = function (id) {
  return "string" == typeof id ? document.getElementById(id) : id;
};
var Extend = function(destination, source) {
 for (var property in source) {
 destination[property] = source[property];
 }
 return destination;
}
var Map = function(array, callback, thisObject){
 if(array.map){
 return array.map(callback, thisObject);
 }else{
 var res = [];
 for (var i = 0, len = array.length; i < len; i++) { res.push(callback.call(thisObject, array[i], i, array)); }
 return res;
 }
}
var ColorGrads = function(options){
 this.SetOptions(options);
 this.StartColor = this.options.StartColor;
 this.EndColor = this.options.EndColor;
 this.Step = Math.abs(this.options.Step);
};
ColorGrads.prototype = {
 //设置默认属性
 SetOptions: function(options) {
  this.options = {//默认值
 StartColor: "#fff",//开始颜色
 EndColor: "#000",//结束颜色
 Step: 20//渐变级数
  };
  Extend(this.options, options || {});
 },
 //获取渐变颜色集合
 Create: function() {
 var colors = [],
 startColor = this.GetColor(this.StartColor),
 endColor = this.GetColor(this.EndColor),
 stepR = (endColor[0] - startColor[0]) / this.Step,
 stepG = (endColor[1] - startColor[1]) / this.Step,
 stepB = (endColor[2] - startColor[2]) / this.Step;
 //生成颜色集合
 for(var i = 0, n = this.Step, r = startColor[0], g = startColor[1], b = startColor[2]; i < n; i++){
 colors.push([r, g, b]); r += stepR; g += stepG; b += stepB;
 }
 colors.push(endColor);
 //修正颜色值
 return Map(colors, function(x){ return Map(x, function(x){
 return Math.min(Math.max(0, Math.floor(x)), 255);
 });});
 },
 //获取颜色数据
 GetColor: function(color) {
 if(/^#[0-9a-f]{6}$/i.test(color))
 {//#rrggbb
 return Map([color.substr(1, 2), color.substr(3, 2), color.substr(5, 2)],
  function(x){ return parseInt(x, 16); }
 )
 }
 else if(/^#[0-9a-f]{3}$/i.test(color))
 {//#rgb
 return Map([color.substr(1, 1), color.substr(2, 1), color.substr(3, 1)],
  function(x){ return parseInt(x + x, 16); }
 )
 }
 else if(/^rgb(.*)$/i.test(color))
 {//rgb(n,n,n) or rgb(n%,n%,n%)
 return Map(color.match(/\d+(\.\d+)?\%?/g),
  function(x){ return parseInt(x.indexOf("%") > 0 ? parseFloat(x, 10) * 2.55 : x, 10); }
 )
 }
 else
 {//color
 var mapping = {"red":"#FF0000"};//略
 color = mapping[color.toLowerCase()];
 if(color){
  return Map([color.substr(1, 2), color.substr(3, 2), color.substr(5, 2)],
  function(x){ return parseInt(x, 16); }
  )
 }
 }
 }
};
var CurrentStyle = function(element){
 return element.currentStyle || document.defaultView.getComputedStyle(element, null);
}
var Bind = function(object, fun) {
 var args = Array.prototype.slice.call(arguments).slice(2);
 return function() {
 return fun.apply(object, args.concat(Array.prototype.slice.call(arguments)));
 }
}
//渐变对象
var ColorTrans = function(obj, options){
 this._obj = $(obj);
 this._timer = null;//定时器
 this._index = 0;//索引
 this._colors = [];//颜色集合
 this._grads = new ColorGrads();
 this.SetOptions(options);
 this.Speed = Math.abs(this.options.Speed);
 this.CssColor = this.options.CssColor;
 this._startColor = this.options.StartColor || CurrentStyle(this._obj)[this.CssColor];
 this._endColor = this.options.EndColor;
 this._step = Math.abs(this.options.Step);
 this.Reset();
 this.SetColor();
};
ColorTrans.prototype = {
 //设置默认属性
 SetOptions: function(options) {
 this.options = {//默认值
 StartColor: "",//开始颜色
 EndColor: "#000",//结束颜色
 Step: 20,//渐变级数
 Speed: 20,//渐变速度
 CssColor: "color"//设置属性(Scripting属性)
 };
  Extend(this.options, options || {});
 },
 //重设颜色集合
 Reset: function(color) {
 //修改颜色后必须重新获取颜色集合
 color = Extend({ StartColor: this._startColor, EndColor: this._endColor, Step: this._step }, color || {});
 //设置属性
 this._grads.StartColor = this._startColor = color.StartColor;
 this._grads.EndColor = this._endColor = color.EndColor;
 this._grads.Step = this._step = color.Step;
 //获取颜色集合
 this._colors = this._grads.Create();
 this._index = 0;
 },
 //颜色渐入
 FadeIn: function() {
 this.Stop(); this._index++; this.SetColor();
 if(this._index < this._colors.length - 1){
 this._timer = setTimeout(Bind(this, this.FadeIn), this.Speed);
 }
 },
 //颜色渐出
 FadeOut: function() {
 this.Stop(); this._index--; this.SetColor();
 if(this._index > 0){
 this._timer = setTimeout(Bind(this, this.FadeOut), this.Speed);
 }
 },
 //颜色设置
 SetColor: function() {
 var color = this._colors[Math.min(Math.max(0, this._index), this._colors.length - 1)];
 this._obj.style[this.CssColor] = "rgb(" + color[0] + "," + color[1] + "," + color[2] + ")";
 },
 //停止
 Stop: function() {
 clearTimeout(this._timer);
 }
};
</script>
</head>
<body>
<style type="text/css">
#idGrads{}
#idGrads div{ font-size:0;height:1px;}
</style>
<div id="idGrads"> </div>
<script>
var forEach = function(array, callback, thisObject){
 if(array.forEach){
 array.forEach(callback, thisObject);
 }else{
 for (var i = 0, len = array.length; i < len; i++) { callback.call(thisObject, array[i], i, array); }
 }
}
var colors = new ColorGrads({ StartColor: "#fff", EndColor: "rgb(20,127,0)" }).Create();
forEach(colors.concat().concat(colors.reverse()), function(x){
 $("idGrads").innerHTML += "<div style=\"background-color:"+"rgb(" + x[0] + "," + x[1] + "," + x[2] + ");\"></div>";
})
</script>
<Br />
<Br />
<style type="text/css">
#idMenu{ background:#DBDBDB;text-align:center;line-height:25px; table-layout:fixed;}
#idMenu td{ cursor:pointer;}
</style>
<table id="idMenu" width="600" border="0" cellspacing="5" cellpadding="0">
 <tr>
 <td onclick="location.href='#'">Cropper</td>
 <td onclick="location.href='#'">Tween</td>
 <td onclick="location.href='#'">Slider</td>
 <td onclick="location.href='#'">Resize</td>
 <td onclick="location.href='#'">Drag</td>
 </tr>
</table>
<script>
forEach($("idMenu").getElementsByTagName("td"), function(x, i){
 var ct1 = new ColorTrans(x, { StartColor: "#666", EndColor: "#fff" });
 var ct2 = new ColorTrans(x, { StartColor: "#f6f6f6", EndColor: "rgb(20,150,0)", CssColor: "backgroundColor" });
 x.onmouseover = function(){ ct1.FadeIn(); ct2.FadeIn(); }
 x.onmouseout = function(){ ct1.FadeOut(); ct2.FadeOut(); }
})
</script>
<Br />
<Br />
<div id="idRandom" style="padding:10px;color:#fff; background-color:#CCC;">点击随机换颜色</div>
<script>
var ctRandom = new ColorTrans("idRandom", { EndColor: "#CCC", CssColor: "backgroundColor" })
$("idRandom").onclick = function(){
 var rgb = Map([1,1,1], function(){ return Math.floor((Math.random() * 255)); } );
 ctRandom.Reset({ StartColor: this.style.backgroundColor, EndColor: "rgb(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + ")" })
 ctRandom.FadeIn();
}
</script>
</body>
</html>
Javascript 相关文章推荐
textContent在Firefox下与innerText等效的属性
May 12 Javascript
使用jQuery的将桌面应用程序引入浏览器
Nov 19 Javascript
javascript 树形导航菜单实例代码
Aug 13 Javascript
JavaScript数据类型判定的总结笔记
Jul 31 Javascript
判断JS对象是否拥有某属性的方法推荐
May 12 Javascript
Javascript中的对象和原型(二)
Aug 12 Javascript
jQuery树插件zTree使用方法详解
May 02 jQuery
JS实现的计数排序与基数排序算法示例
Dec 04 Javascript
学习React中ref的两个demo示例
Aug 14 Javascript
vue 中引用gojs绘制E-R图的方法示例
Aug 24 Javascript
微信小程序实现留言板功能
Nov 02 Javascript
详解JS对象封装的常用方式
Dec 30 #Javascript
Jquery EasyUI Datagrid右键菜单实现方法
Dec 30 #Javascript
jQuery与js实现颜色渐变的方法
Dec 30 #Javascript
javascript工厂模式和构造函数模式创建对象方法解析
Dec 30 #Javascript
ajax图片上传,图片异步上传,更新实例
Dec 30 #Javascript
浅谈JavaScript的函数及作用域
Dec 30 #Javascript
解析ajaxFileUpload 异步上传文件简单使用
Dec 30 #Javascript
You might like
2020最新CPU的性能排名
2020/04/02 数码科技
php的一个登录的类 [推荐]
2007/03/16 PHP
Linux下CoreSeek及PHP扩展模块的安装
2012/09/23 PHP
浅析PHP substr,mb_substr以及mb_strcut的区别和用法
2013/06/21 PHP
yii2 在控制器中验证请求参数的使用方法
2019/06/19 PHP
Jquery右下角抖动、浮动 实例代码(兼容ie6、FF)
2013/08/15 Javascript
使用时间戳解决ie缓存的问题
2014/08/20 Javascript
浅谈jQuery页面的滚动位置scrollTop、scrollLeft
2015/05/19 Javascript
轻量级jQuery插件slideBox实现带底栏轮播(焦点图)代码
2016/03/28 Javascript
JS实现table表格数据排序功能(可支持动态数据+分页效果)
2016/05/26 Javascript
【经典源码收藏】jQuery实用代码片段(筛选,搜索,样式,清除默认值,多选等)
2016/06/07 Javascript
Node.js的文件权限及读写flag详解
2016/10/11 Javascript
Nodejs基于LRU算法实现的缓存处理操作示例
2017/03/17 NodeJs
详解利用 Express 托管静态文件的方法
2017/09/18 Javascript
在Vue中使用highCharts绘制3d饼图的方法
2018/02/08 Javascript
AngularJS监听ng-repeat渲染完成的方法
2018/03/20 Javascript
Bootstrap 时间日历插件bootstrap-datetimepicker配置与应用小结
2019/05/28 Javascript
npm的lock机制解析
2019/06/20 Javascript
Vue + Element UI图片上传控件使用详解
2019/08/20 Javascript
node.js中 redis 的安装和基本操作示例
2020/02/10 Javascript
[05:49]DOTA2-DPC中国联赛 正赛 Elephant vs LBZS 选手采访
2021/03/11 DOTA
[07:01]DOTA2-DPC中国联赛正赛 Aster vs Magma 3月5日 赛后选手采访
2021/03/11 DOTA
Python 获得命令行参数的方法(推荐)
2018/01/24 Python
磁盘垃圾文件清理器python代码实现
2020/08/24 Python
Django 登陆验证码和中间件的实现
2018/08/17 Python
python 多线程对post请求服务器测试并发的方法
2019/06/13 Python
会计电算化专业个人的自我评价
2013/11/24 职场文书
房地产推广策划方案
2014/05/19 职场文书
无毒社区工作方案
2014/05/23 职场文书
小学语文教研活动总结
2014/07/01 职场文书
中学生关于梦想的演讲稿
2014/08/22 职场文书
2015年禁毒工作总结
2015/04/30 职场文书
幼儿园亲子活动感想
2015/08/07 职场文书
民警忠诚教育心得体会
2016/01/23 职场文书
python spilt()分隔字符串的实现示例
2021/05/21 Python
JS高级程序设计之class继承重点详解
2022/07/07 Javascript