style代码
#box1{
height: 100px;
width: 200px;
background: #bfa;
border: 2px solid red;
}
body代码
<body>
<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.οnclick=function(){
// alert("绑定成功");
addElement();
changeColor();
}
// **在随机生成图片的基础上,加上随机改变页面的背景色
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+")";
}
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="img/3.jpg";
var body=document.body;
body.appendChild(box);
}
</script>