javaScript中appendChild的用法

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其实就是在某个节点里面添加一个新的子节点

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值