JS:需要一个基于字符串的CSS颜色代码 [英] JS: need a css color code based on a string
本文介绍了JS:需要一个基于字符串的CSS颜色代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个函数来生成一个CSS颜色,范围为 min:#000000
和 max:#FFFFFF
。如果输入字符串的长度或任何字符发生变化,函数应该返回不同的颜色(但是它必须在同一个字符串输入上返回相同的颜色)。
I need a function to generate a CSS color based on a string with a range of min: #000000
and max: #FFFFFF
. If the length or any of the characters in the input string changes, the function should return a different color (but it must always return the same color on the same string input).
例如:
f("Reddit") ==>#FF0000
f("Smith") ==>#FFC0CB
f("Smixh")==>#F008FF
f("Smith") ==>#FFC0CB
f("foo")==>#FF00FF
f("Reddit") ==>#FF0000
等等。任何想法如何做?
And so on. Any idea how to do that?
推荐答案
我会散列字符串,并使用十六进制校验和的前六个字符作为十六进制颜色代码:
I'd hash the string and use the first six characters of the hex checksum as your hex color code:
function color(string) {
return '#' + md5(string).slice(0, 6);
}
演示: http://jsfiddle.net/4PMnA/48/
Demo: http://jsfiddle.net/4PMnA/48/
这篇关于JS:需要一个基于字符串的CSS颜色代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文