function getColorCSS(c) {
\t var ele = document.createElement("div");
\t ele.style.color = c;
\t return ele.style.color.split(/\s+/).join('').toLowerCase();
}
function isColorValid(c) {
\t var s = getColorCSS(c);
\t return (s) ? true : false;
}
function isColorTransparent(c) {
\t var s = getColorCSS(c);
\t return (
\t \t s === "transparent" ||
\t \t s.substring(0,4) === "rgba" && +s.replace(/^.*,(.+)\)/,'$1') <= 0 ||
\t \t s.substring(0,4) === "hsla" && +s.replace(/^.*,(.+)\)/,'$1') <= 0
\t);
}
function isColorWhite(c) {
\t var s = getColorCSS(c);
\t return [
\t \t "white",
\t \t "rgb(255,255,255)",
\t \t "rgba(255,255,255,1)",
\t \t "hsl(0,0%,100%)",
\t \t "hsla(0,0%,100%,1)"
\t ].indexOf(s) > -1;
}
function isColorBlack(c) {
\t var s = getColorCSS(c);
\t return [
\t \t "black",
\t \t "rgb(0,0,0)",
\t \t "rgba(0,0,0,1)",
\t \t "hsl(0,0%,0%)",
\t \t "hsla(0,0%,0%,1)"
\t ].indexOf(s) > -1;
}
function checkColorString() {
var c = document.getElementById("c").value;
if (c === "") {
document.getElementsByTagName("body")[0].style.backgroundColor = 'transparent';
document.getElementById("result").innerHTML = '';
}
else if (isColorValid(c)) {
if (isColorTransparent(c)) {
document.getElementsByTagName("body")[0].style.backgroundColor = 'transparent';
document.getElementById("result").innerHTML = '<span style="color:#dadada;">TRANSPARENT</span>';
}
else if (isColorWhite(c)) {
document.getElementsByTagName("body")[0].style.backgroundColor = getColorCSS(c);
document.getElementById("result").innerHTML = '<span style="color:black;">WHITE</span>';
}
else if (isColorBlack(c)) {
document.getElementsByTagName("body")[0].style.backgroundColor = getColorCSS(c);
document.getElementById("result").innerHTML = '<span style="color:white;">BLACK</span>';
}
else {
document.getElementsByTagName("body")[0].style.backgroundColor = getColorCSS(c);
document.getElementById("result").innerHTML = getColorCSS(c);
}
}
else {
document.getElementsByTagName("body")[0].style.backgroundColor = 'transparent';
document.getElementById("result").innerHTML = '<span style="font-size:42px;color:#dadada;">☹</span>';
}
}
var eventList = ["change", "keyup", "paste", "input", "propertychange"];
for(event of eventList) {
document.getElementById("c").addEventListener(event, function() {
checkColorString();
});
}
#c {
width: 300px;
padding: 6px;
font-family: courier;
}
#result {
font-family: courier;
font-size: 24px;
padding: 12px 6px;
}
<input id="c" placeholder="Enter any valid CSS color..."></input>
<div id="result"></div>
非常有趣的問題。我喜歡。 – Patricia 2011-06-17 13:03:33
我以爲只有17個(數橙色)? – kennebec 2011-06-17 13:17:38
@kennebec:看到http://www.w3schools.com/css/css_colornames.asp – SystemicPlural 2011-06-17 13:42:38