分享一個為div
設置隨機顏色的小trick,來自于知乎。
表達式:
Math.floor(Math.random()*(2<<23)).toString(16);
分步解析
各種表達式解釋:
-
Math.floor()
向下取整,可以理解為取浮點數(shù)的整數(shù)位;
相似的用法:
Math.ceil()
向上取整;Math.round()
四舍五入 -
Math.random()
生成隨機數(shù),范圍(0-1),在后面乘幾(n),代表取該范圍(0-->n)的隨機數(shù) -
2<<23
<<左移運算符,此操作將2進制10變?yōu)?000...00,即左移23位; -
toString(16)
生成16進制的字符串;
具體解釋
-
Math.random()*(2<<23)
取0-(2<<23)之間的隨機數(shù),即取十進制(0-16777216)之間的隨機數(shù)
(之所以這樣設置,是因為16進制數(shù)ffffff
的十進制表示方式為16777215
) -
Math.floor(Math.random()*(2<<23))
對生成的隨機數(shù)向下取整,即保留隨機數(shù)的整數(shù)部分 -
.toString(16)
把生成的隨機數(shù)(十進制)轉(zhuǎn)換為16進制,并轉(zhuǎn)換為數(shù)組
可視化結果
<html>
<body>
<script type="text/javascript">
var random=Math.random(); //生成隨機數(shù):0.32273213103830223
var demo= (2<<23); //十進制數(shù):16777216
var list=random*demo; //生成代表顏色的隨機數(shù):5414546.672569901
var num=Math.floor(list); //向下取整:5414546
document.write(num.toString(16)) //生成隨機顏色:529e92
</script>
</body>
</html>
通過上述做法,達到了生成隨機顏色值的效果。如此,可以畫很多有趣的圖形了。
具體應用
比如說,現(xiàn)在要做一個“挑選幸運色(晃瞎你雙眼)”的頁面,利用顏色值隨機數(shù)可以完成。
以下是代碼:
<!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函數(shù)來生成隨機顏色并通過停止按鈕來選擇幸運色;當然,設置隨機高寬是為了晃瞎雙眼。
運行效果見:https://github.com/cyuamber/randomcolor