一个网页颜色选择器的js

花了一个晚上,有javascript写了一个网页的颜色选择器。

最终效果是





  使用方法     代码 color.js
var ____setcolor = null;
function initcolor(evt)
 {
	var ColorHex = new Array('00','33',  '66', '99', 'CC', 'FF');
	var line = 18;
    var colortable = "<div style='float:right;right:5px; font-size:14px;cursor:pointer;' onclick='colorclose()'>x关闭</div>";
	colortable += "<div style='float:right;margin-right:10px; font-size:14px;cursor:pointer;' onclick='defaultColor()'>默认颜色</div>";
	colortable  += "<div style='clear:both;board:0;'/>"
	colortable  += "<table border='1' rules='all'><thead height=1>";
	colortable += "</thead><tbody><tr height=12>";
	var i = 0;
	 for(r in ColorHex){
		 for(g in ColorHex){
			 for(b in ColorHex){
				 var color =  '#' + ColorHex[r] + ColorHex[g] + ColorHex[b];
				 if( i == line){
					 i = 0;
					 colortable += "</tr><tr height=12>";
				 }
				 colortable += "<td width=12 style='cursor:pointer;background-color:"+ color + ";' onclick='doclick(\"" + color+  "\")' />" 
				 i++;
			 }
		 }
	 }
	 colortable += '</tr></tbody></table>';
	 document.getElementById("colorpane").innerHTML = colortable;;
}
function doclick(colorValue) {
    ____setcolor(colorValue);
    document.getElementById("colorpane").style.display = "none";
}
function defaultColor() {
    ____setcolor("");
    document.getElementById("colorpane").style.display = "none";
}
function colorclose() {
    document.getElementById("colorpane").style.display = "none";
}

function coloropen(func) { 
	src = event.srcElement;
	____setcolor = func;
	var pan = document.getElementById("colorpane");
	pan.style.left = getLeft (src) + src.clientWidth + 10 +"px";
	pan.style.top = getTop(src) + src.clientHeight + 5 + "px";
	pan.style.display = "";
}
window.onload = function()
{
	var pan = document.createElement("div");
	pan.id = "colorpane";
	pan.style.position = "absolute";
	pan.style.zIndex = "999";
	pan.style.display = "none" ;
	pan.style.padding= 5 + "px";
	pan.style.border = "2px solid #000000";
	pan.style.background = "white";
	document.body.appendChild(pan);
    initcolor();
}
function getTop(e){ 
var returnValue = e.offsetTop;
while((e = e.offsetParent) != null)returnValue += e.offsetTop;
return returnValue;
} 
//获取元素的横坐标 
function getLeft(e){ 
var returnValue = e.offsetLeft;
while((e = e.offsetParent) != null)returnValue += e.offsetLeft;
return returnValue;
}
 

文章来源:http://blog.xujif.com/archives/a-html-js-color-selector/
posted @ 2011-11-06 12:57  xujif  阅读(219)  评论(0编辑  收藏  举报