074|节点操作实例

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>074节点操作实例</title>
		<style>
			#div1{width:400px;height: 100px;background-color: orange;}
			#div2{width:400px;height: 500px;background-color: peachpuff;}
			#input1{width:380px;height:30px;font-size: 18px;}
			#div1 button{width:100px;height: 30px;font-size:18px;background-color: black;color: white;margin-left: 5px;margin-top: 5px;}
		</style>
		<script>
			function randomColor(){
				var color="rgba("+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+","+parseInt(Math.random()*256)+",1)";
				return color;
			}
			window.onload=function(){
				var oDiv1=document.getElementById("div1");
				var oDiv2=document.getElementById("div2");
				var oInput=document.getElementById("input1");
				
				//获取div1下main所有的button
				var aBtns=oDiv1.getElementsByTagName("button");
				//分别给三个按钮添加不同的点击函数
				aBtns[0].onclick=function(){
					if(!oInput.value){
						alert("输入的内容不为空");
					}else{
						//获取到输入框的内容,创建页面添加到页面上
						var newDiv=document.createElement("div");
						var oTxt=document.createTextNode(oInput.value);
						newDiv.appendChild(oTxt);
						newDiv.style.backgroundColor=randomColor();
						oDiv2.appendChild(newDiv);
						oInput.value="";
					}
				}
				aBtns[1].onclick=function(){
					//删除最后一个节点
					oDiv2.removeChild(oDiv2.lastChild);
				}
				aBtns[2].onclick=function(){
					//拷贝最后一个节点,再添加到节点上
					var newNode=oDiv2.lastChild.cloneNode(true);
					oDiv2.appendChild(newNode);
				}
			}
		</script>
	</head>
	<body>
		<div id="div1">
			<input type="text" id="input1" placeholder="输入内容" /><br />
			<button>增加</button>
			<button>删除</button>
			<button>拷贝</button>
		</div>
		<div id="div2"></div>
		<!--  <div>xxx<button>x</button></div>
		    <div>xxx<button>x</button></div>
			  <div>xxx<button>x</button></div> -->
	</body>
</html>

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值