分享一個為div
設置隨機顏色的小trick捧请,來自于知乎帮孔。
表達式:
Math.floor(Math.random()*(2<<23)).toString(16);
分步解析
各種表達式解釋:
-
Math.floor()
向下取整岁歉,可以理解為取浮點數的整數位付燥;
相似的用法:
Math.ceil()
向上取整欺劳;Math.round()
四舍五入 -
Math.random()
生成隨機數筝闹,范圍(0-1),在后面乘幾(n)蕉朵,代表取該范圍(0-->n)的隨機數 -
2<<23
<<左移運算符崔涂,此操作將2進制10變?yōu)?000...00,即左移23位始衅; -
toString(16)
生成16進制的字符串冷蚂;
具體解釋
-
Math.random()*(2<<23)
取0-(2<<23)之間的隨機數缭保,即取十進制(0-16777216)之間的隨機數
(之所以這樣設置,是因為16進制數ffffff
的十進制表示方式為16777215
) -
Math.floor(Math.random()*(2<<23))
對生成的隨機數向下取整蝙茶,即保留隨機數的整數部分 -
.toString(16)
把生成的隨機數(十進制)轉換為16進制艺骂,并轉換為數組
可視化結果
<html>
<body>
<script type="text/javascript">
var random=Math.random(); //生成隨機數:0.32273213103830223
var demo= (2<<23); //十進制數:16777216
var list=random*demo; //生成代表顏色的隨機數:5414546.672569901
var num=Math.floor(list); //向下取整:5414546
document.write(num.toString(16)) //生成隨機顏色:529e92
</script>
</body>
</html>
通過上述做法,達到了生成隨機顏色值的效果隆夯。如此钳恕,可以畫很多有趣的圖形了。
具體應用
比如說蹄衷,現在要做一個“挑選幸運色(晃瞎你雙眼)”的頁面忧额,利用顏色值隨機數可以完成。
以下是代碼:
<!DOCTYPE html>
<html>
<head>
<title>晃瞎你雙眼</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.8.0.js"></script>
<script type="text/javascript">
var randomColor, randomHeight, randomWidth;
function changeTrangel () {
//生成隨機顏色
randomColor = '#'+Math.floor(Math.random()*(2<<23)).toString(16);
//生成隨機高度
randomHeight = Math.floor(Math.random()*($(".container").height()))+200+'px';
//生成隨機寬度
randomWidth = Math.floor(Math.random()*($(".container").width()))+500+'px';
$(".box1")
.css("background-color",randomColor)
.css("height",randomHeight)
.css("width",randomWidth);
$(".colorholder").text(randomColor)
}
var int=self.setInterval("changeTrangel()",100);
function startChange () {
window.location.reload();
}
function stopChange () {
int=window.clearInterval(int)
}
</script>
<style type="text/css">
.container{
margin: 30px;
width: 80%;
}
</style>
</head>
<body>
<h1>看看你的幸運顏色</h1>
<button class='button' id="buttonstart" onclick="startChange()">開始</button>
<button class='button' id="buttonstop" onclick="stopChange()" >停止</button>
<h2 class="colorholder"></h2>
<div class="container">
<div class="box box1"></div>
<div class="box box2"></div>
</div>
</body>
</html>
這里邊的核心功能在于宦芦,通過random函數來生成隨機顏色并通過停止按鈕來選擇幸運色宙址;當然,設置隨機高寬是為了晃瞎雙眼调卑。
運行效果見:https://github.com/cyuamber/randomcolor