代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#box1{
height: 100px;
width: 200px;
background: #bfa;
border: 2px solid red;
}
</style>
</head>
<body>
<!-- <div id="box1"></div> -->
<!-- <input type="button" value="新增元素" onclick="addElement()"> -->
<input type="button" id="btn_1" value="新增元素">
获取焦点事件:<input type="text" id="input_1">
</body>
<script>
//实现在js代码中绑定事件
//1、获取事件源对象,按钮
var button=document.querySelector("#btn_1");
var input_1=document.querySelector("#input_1");
//2、绑定事件
button.onclick=function(){
// alert("绑定成功");
addElement();
changeColor();
// var bgColor="";
// for(var i=0; i<6; i++){
// bgColor += '' + Math.round(Math.random()*9);
// }
// document.body.style.backgroundColor='#'+bgColor;
}
// button.onclick=false;
// **在随机生成图片的基础上,加上随机改变页面的背景色
function changeColor(){
var body=document.body;
var R=Math.random()*255;
var G=Math.random()*255;
var B=Math.random()*255;
body.style.backgroundColor="rgb("+R+","+G+","+B+")";
}
//3、addEventlistener
//添加事件监听器
// button.addEventListener("click",addElement);
// button.addEventListener("click",changeColo);
// button.addEventListener("click",function(){
// alert("绑定成功");
// })
// button.removeEventListener("click",addElement);
// button.addEventListener("click",test);
/* d对比绑定事件的三种方式
1.行内绑定
写在哪个标签就是给哪个标签绑定事件
无法通过代码实现给多个元素同时绑定事件
2.元素.onclick()
同一个元素相同的时间只能绑定一次,以后绑定的事件为准
3.元素.addEventListerner()
同一个元素可以添加多个事件监听器,都会执行,后添加的监听器先执行
*/
function addElement(){
//实现向页面添加元素
var box=document.createElement("img");
box.style.width="100px";
box.style.height="100px";
box.style.backgroundColor="#bfa";
box.style.position="absolute";
box.style.left=Math.random()*800+"px";
box.style.top=Math.random()*200+"px";
box.src="1.jpg";
var body=document.body;
body.appendChild(box);
}
// var box=document.querySelector("#box1");
// alert(box.getAttribute("id"));
// box.setAttribute("class","box");
// //如何修改页面元素样式
// box.style.border="0px solid red";
// box.className="boxType";
</script>
</html>
实现效果: