问题描述
我是java-script的新手。每当我调用特定函数时,我都需要获得随机背景颜色。
I am new to java-script . I need to get a random background color whenever i call a particular function.
我在网上找到了以下代码,但我不太明白它是如何工作的。
I found the following code on the web but i don't quite understand how it works.
代码:
function getRandomColor () {
var hex = Math.floor(Math.random() * 0xFFFFFF);
return "#" + ("000000" + hex.toString(16)).substr(-6);
}
以上代码是如何工作的。我理解Math.random()的工作原理但 hex.toString(16))。substr(-6)
基本上是什么意思?
How is the above code working.I understand how Math.random() works but what does hex.toString(16)).substr(-6)
basically signify?
可以请向我说明上述代码是如何工作的。
Can some one please clarify it to me how the above code works.
推荐答案
function getRandomColor () {
var hex = Math.floor(Math.random() * 0xFFFFFF);
return "#" + ("000000" + hex.toString(16)).substr(-6);
}
hex.toString(16)
将十六进制转换为基数 16
中的字符串数字表示。
hex.toString(16)
converts hex into string number representation in base 16
.
语法:
number.toString(radix)
radix:
用于表示数值的基数。必须是2到36之间的整数。
radix:
Base to use for representing a numeric value. Must be an integer between 2 and 36.
2 - The number will show as a binary value
8 - The number will show as an octal value
16 - The number will show as an hexadecimal value
substr(-6)
只取最后6个字符,这会切断000000
,因为它们不是最后6个字符的一部分。
substr(-6)
just takes the last 6 characters, which cuts off the "000000"
because they're not part of the last 6 characters.
这篇关于在javascript中获取随机背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!