现在的位置: 首页 > 综合 > 正文

关于DOM的一些实例探讨

2018年05月20日 ⁄ 综合 ⁄ 共 1895字 ⁄ 字号 评论关闭

1.下面是关于验证DOM的某些节点属性和触发按钮点击事件后显示一张图片的实例

<!DOCTYPE html>
<html>
<head>
<title>dom.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript">
	window.onload = function() {
		var button1 = document.getElementById("button1");
		var div1 = document.getElementById("div1");
		button1.onclick = function() {
			div1.innerHTML = "<img src='2.jpg'/>";
			document.getElementsByTagName("p");
		};
	};
</script>
</head>

<body>
	<p>a</p>
	<p>b</p>
	<div id="div1"></div>
	<input type="button" value="按钮" id="button1">
</body>
</html>

效果图:

没有触发按钮之前

触发按钮之后:

2.动态创建节点

<!DOCTYPE html>
<html>
  <head>
    <title>dom2.html</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">    
<script>
window.onload=function(){
	var button1 = document.getElementById("button1");
	var div1 = document.getElementById("div1");
	button1.onclick= function(){
		var img1 = document.createElement("img");
		//第一种实现方法
		img1.src = "1.jpg";
		//第二种实现方法
		//img1.setAttribute("src","2.jpg");
		div1.appendChild(img1);
		
	};
	};
	</script>
  </head> 
  <body>动态创建节点
   <div id = "div1"></div>
    <input type = "button" value="创建新节点" id="button1">
  </body>
</html>

效果图:

点击一次鼠标出现一次图标。

 

 

 

上面的例子可以通过生成随机数并拼凑字符串来插入不同的图片

var n = parseInt(Math.random() * 4 + 1);
img1.src = n + ".jpg";

3.在div的上面插入图片,而不是div内部

<!DOCTYPE html>
<html>
<head>
<title>dom4.html</title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

<script>
	window.onload = function() {
		var button1 = document.getElementById("button1");
		var div1 = document.getElementById("div1");
		button1.onclick = function() {
			var img1 = document.createElement("img");
			img1.height = 130;
			img1.width = 130;
			var n = parseInt(Math.random() * 4 + 1);
			//第一种实现方法
			img1.src = n + ".jpg";
			//第二种实现方法
			//img1.setAttribute("src","2.jpg");

			//div1.appendChild(img1);
			div1.parentNode.insertBefore(img1, div1);
		};
	};
</script>
</head>

<body>
	循环动态创建节点
	<div id="div1">
		<img src="4.jpg" />
	</div>

	<input type="button" value="创建新节点" id="button1">
</body>
</html>

程序加载后的效果:

多次点击按钮后的效果:

 

                                                                                        

 

抱歉!评论已关闭.