1.appendChild() 方法可向节点的子节点末尾添加新的子节点。
实例一:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
.map{
width: 800px;
height: 500px;
background-color:gray;
position: relative;
}
</style>
<body>
<div class="map"></div>
<script>
(function(window){//封装的以随机数对象
function Random(){
}
Random.prototype.init=function(min,max){
return Math.floor(Math.random()*(max-min)+min)
}
window.getrandom=new Random()
})(window);
(
function(window){
function Food(width,height,color){
this.width=width||20
this.height=height||20
this.color=color
var x,y=0
this.element=document.createElement('div')
// div.style.position='absolute'
// div.style.left=x
// div.style.top=y
}
Food.prototype.init=function(map,window){
var div=this.element
div.style.position='absolute'
div.style.width=this.width+"px"
div.style.height=this.height+"px"
div.style.backgroundColor=this.color
map.appendChild(div)
this.render(map,window)
}
Food.prototype.render=function(map,window){
console.log(map.offsetWidth)
console.log(map.offsetHeight)
var x=window.getrandom.init(0,map.offsetWidth/this.width)*this.width
var y=window.getrandom.init(0,map.offsetHeight/this.height)*this.height
this.x=x
this.y=y
var div=this.element
div.style.left=this.x+"px"
div.style.top=this.y+"px"
}
var fd=new Food(20,20,"green")
var map=document.querySelector('.map')
fd.init(map,window)
}
)(window);
</script>
</body>
</html>
总结:使用appendChild其实就是在某个节点里面添加一个新的子节点