JS学习十二:DOM节点动态操作,飞翔的球示例
创建一个a标签、插入到div元素节点之下:
- 创建标签: document.createElement(标签名)
- 通过id,获取元素节点:document.getElementById(id值)
- 插入子节点:元素节点.appendChild(标签名)
注意div与子节点之间,不能有换行、空白,否则会多出一个div的文本节点。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <style type="text/css"> #box { width: 200px; height: 200px; background-color: red; } </style> </head> <body style="height: 1000px;"> <div id="box"> <p>我是第一个</p> <p>我是第二个</p> </div> <script type="text/javascript"> // 创建一个a标签 var a = document.createElement("p") a.innerHTML = "我是第三个" a.style.backgroundColor = "red" console.log(a) // 查找元素节点 var div = document.getElementById("box") // 为元素节点DIV,添加子节点,即插入标签 div.appendChild(a) </script> </body> </html>
创建一个a标签、插入到div元素节点最后一个子节点之前:
//在元素节点的最后一个子节点p之前,插入一个a标签
div.insertBefore(a, div.lastChild)
创建文本节点:document.createTextNode(内容)
替换节点:
//用a标签,替换div元素节点的最后一个子节点
div.replaceChild(a, div.lastChild)
复制节点:
//复制节点:有参数true,包括子节点
var new div = div.cloneNode(true)
删除节点:
//删除节点
div.removeChild(div.lastChild)
示例:
创建input标签
<script type="text/javascript"> var input = document.createElement("input") input.setAttribute("type", "text") input.setAttribute("placeholder", "good") document.getElementById("box").appendChild(input) </script>
示例:飞翔的球.......
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <style type="text/css"> #box { width: 600px; height: 400px; border: solid 1px red; position: relative; } #ball { width: 50px; height: 50px; border-radius: 25px; background-color: yellow; position: absolute; top: 0; left: 0; } </style> </head> <body style="height: 1000px;"> <div id="box"> <div id="ball"> </div> </div> <script type="text/javascript"> var ball = document.getElementById("ball") var speedx = 2 var speedy = 2 setInterval(function () { ball.style.left = ball.offsetLeft + speedx + "px" ball.style.top = ball.offsetTop + speedy + "px" if (ball.offsetTop >= 400 - 50 || ball.offsetTop <= 0) { speedy *= -1 } if (ball.offsetLeft >= 600 -50 || ball.offsetLeft <= 0) { speedx *= -1 } }, 10) </script> </body> </html>
233
posted on 2018-11-18 23:50 myworldworld 阅读(111) 评论(0) 收藏 举报