document.body.appendChild() 和 element.appendChild() 的区别
使用的时候很容易搞混,今天抽空来捋一捋。
首先要搞清楚:
document.body 代表的当前文档的body对象
document.documentElement 代表的是当前的完整文档
使用方法:
var x=document.createElement(“div”);
在body上挂载元素:document.body.appendChild(x)
在一个元素上挂载该元素:element.appendChild(x);
下面举个例子:
在body中的随机位置添加一张图片
//创建一个图片标签
var e_img=document.createElement("img");
e_img.src=".../img/1.jpg"; //添加图片
e_img.width="30"; //设置大小 或者style.width="30px"
e_img.heighe="30";
//创建一个div
var e_div=document.createElement("div");
e_div.style.width="30px"; //设置大小
e_div.style.width="30px";
e_div.style.position = "fixed"; //设置为绝对定位
e_div.setAttribute("class", "c2"); //为新的div设置选择器
//设置新的div出现位置随机
e_div.style.top = parseInt(Math.random() * 150) + "px";
e_div.style.left = parseInt(Math.random() * window.innerWidth) + "px";
//img挂载到div上
e_div.appendChild(e_img);
//div挂载到body上
document.body.appendChild(e_div);