<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>随机颜色</title>
<style type="text/css">
#app{
position: absolute;
}
</style>
</head>
<body>
<div id="app">
盒子
</div>
</body>
<script type="text/javascript">
init();
function init() {
document.addEventListener("click", click); //监听 点击事件
appRandom(); //随机一次
}
// 点击事件
function click(e){
e=e || window.event
appRandom()
}
//位置随机
function appRandom(){
var apps = document.getElementById("app");
var seat = seatSize(); //seat作为位置大小的数据暂存
cloneObj(apps.style, {
left: seat.left + "px",
top: seat.top + "px",
width: seat.width + "px",
height: seat.height + "px",
backgroundColor:appColor()
})
}
//克隆对象属性
function cloneObj(biaoji, Square) {
for (var key in Square) {
biaoji[key] = Square[key];
}
}
//div大小&位置 随机的变化函数
function seatSize() {
var w = Math.random() * document.documentElement.clientWidth;
var h = Math.random() * document.documentElement.clientHeight;
var x = Math.random() * (document.documentElement.clientWidth - w);
var y = Math.random() * (document.documentElement.clientHeight - h);
return {
left: x,
top: y,
width: w,
height: h
};
}
//随机颜色
function appColor(){
var co = "#"; //字符串第一位为# 颜色的格式
for (let i = 0 ; i < 3; ++i){
co += parseInt(Math.random() * 256).toString(16)
}
return co
}
</script>
</html>
div 随机位置、颜色、大小
于 2020-04-07 15:02:14 首次发布