要求: 点击按钮,随机生成一个20px-100px宽度正方形,随机颜色,随机位置,不能出可视区域外html
思路:(1)建立按钮,为按钮添加事件侦听app
(2)触发事件,建立一个元素dom
(3)设置元素样式,包括大小,位置,颜色函数
基础HTML代码:spa
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button>添加</button>
<script>
</script>
</body>
</html>
JS代码:code
init(); function init() { var bn = document.getElementById("bn"); //经过id获取按钮bn
bn.addEventListener("click",clickHandler); //为按钮添加点击事件
} function clickHandler(e) { var wid = document.documentElement.clientWidth; //获取视口宽度
var hei = document.documentElement.clientHeight; //获取视口高度
var div = document.createElement("div"); //建立一个div
//定义一个局部变量divWidth 存放当前建立的div的大小
var divWidth = Math.floor(Math.random() * 80 + 20); //设置div的样式,包括 宽 高 定位 背景颜色
div.style.position = "absolute"; div.style.width=divWidth+"px"; div.style.height=divWidth+"px"; //div的位置应该是当前视口宽高减去建立div的宽高 而后取随机值,才能保证div不会超出视口
div.style.left = Math.floor(Math.random() * (wid - divWidth))+"px"; div.style.top = Math.floor(Math.random() * (hei - divWidth))+"px"; div.style.backgroundColor =randomColor(); //将元素添加到body中
document.body.appendChild(div); } //定义一个函数,执行返回一个表明颜色的字符串
function randomColor() { return "#"+Math.floor(Math.random()*0x1000000).toString(16).padStart(6,"0"); }
效果展现:htm
看完上面的代码,你是否是以为它看起来有一些 繁杂 也许咱们能够将它 “美化” 一下,让代码看起来更漂亮,更加赏心悦目对象
咱们能够将代码中的一些相似的部分摘取出来,用一个函数来完成这些内容,好比为元素添加style 样式blog
咱们能够这么写事件
// createNewElement 建立一个元素, 函数内有两个参数第一个参数是要建立的元素类型,第二个参数是样式
//经过Object.assign()方法将style内的属性添加给建立的元素的style上
//最后将处理好的元素返回
function createNewElement(elem,style){ var elem=document.createElement(elem); Object.assign(elem.style,style); return elem; }
用于将源对象的全部可枚举属性复制到目标对象中。
咱们怎么使用这个函数呢
var elem(用于接收函数return的元素)=createNewElement("div(要建立的元素类型)",{
属性:属性值; //第二个参数为对象,将这个对象传入,并将对象的属性复制到元素的style属性上完成样式的添加.
width:"100px",
backgroundColor:"green"
});
这个函数不只能够用于这里,还能够用于建立其余元素
init(); function init() { var bn = document.getElementById("bn"); //经过id获取按钮bn
bn.addEventListener("click",clickHandler); //为按钮添加点击事件
} function clickHandler(e) { var wid = document.documentElement.clientWidth; //获取视口宽度
var hei = document.documentElement.clientHeight; //获取视口高度
//定义一个变量divWidth 存放当前建立的div的大小
var divWidth = Math.floor(Math.random() * 80 + 20); var div=createNewElement("div",{ position : "absolute", width:divWidth+"px", height:divWidth+"px", left: Math.floor(Math.random() * (wid - divWidth))+"px", top:Math.floor(Math.random() * (hei - divWidth))+"px", backgroundColor:randomColor() }) document.body.appendChild(div); } // createNewElement 建立一个元素, 函数内有两个参数第一个参数是要建立的元素类型,第二个参数是样式
//经过Object.assign()方法将style内的属性添加给建立的元素的style上
//最后将处理好的元素返回
function createNewElement(elem,style){ var elem=document.createElement(elem); Object.assign(elem.style,style); return elem; } //定义一个函数,执行返回一个表明颜色的字符串
function randomColor() { return "#"+Math.floor(Math.random()*0x1000000).toString(16).padStart(6,"0"); }
--