目录
DOM
简介:
DOM(Document Object Model——文档对象模型)是用来处理HTML和XML的跨平台API。它允许运行在浏览器中的代码访问文档节点并与之交互,了解并掌握DOM操作是Web开发中的必经之路。
整个HTML的结构都可以由类似上图的树结构表示,整个树结构由节点组成
-
document对象指代整个文档节点, 它是文档内其他节点的访问入口,提供了操作其他节点的方法
-
节点可以分为元素节点、文本节点和属性节点
-
节点之间有层级关系,父(parent)、子(child)和同胞(sibling)等术语用于描述这些关系。父节点拥有子节点,同级的子节点被称为同胞(兄弟或姐妹)
树形结构:
就是嵌套(非线性结构)非对称
HTML的标签逻辑就是树形结构
DOM结构
增:
新建:
fn createElemeng(标签名)-------创元素节点
fn setAttribute(name,value)----------直接设置属性
//通过setAttribute属性设置的自定义属性通过点语法无法调用
fn cloneNode(true||false):true 包含子节点;false 不包含
插入:
拼接节点:fn appendChild()
插入节点:fn insertBefore(new,old)
练习:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="wert">
</div>
</body>
<script>
var lsp=document.getElementById("wert");//获取id为wert的节点
var p1=document.createElement("p");//创建了一个p标签,和<p>是一样的,只是没有指定位置
p1.innerHTML="五龙同朝:"//输出在html文档
lsp.appendChild(p1);//将p1作为lsp的子集,这样就将p1的位置给指定了
var arr=["朱元璋","朱允炆","朱棣","朱高炽","朱瞻基"];
for (var i=0;i<arr.length;i++){
var p2=document.createElement("p");
p2.innerHTML=arr[i];
lsp.appendChild(p2);
}
var lsp1=document.getElementsByName("p")[0];//获取所有p元素节点
lsp1.setAttribute("myname","海绵hong");
console.log(lsp.getAttribute("myname"))
var p3=document.createElement("p");
p3.innerHTML="明朝"
lsp.insertBefore(p3,p1);//新的标签为p3替换掉了lsp标签
</script>
</html>
删
删除子节点------fn removeChild(节点名);
删除属性节点-----fn removeAttributeNode();
练习:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="wert">
<p id="1">愿得一人心</p>
<p id="2">换个女朋友</p>
<p id="3">白首不分离</p>
</div>
</body>
<script>
var lsp=document.getElementById("wert");
var lsp1=document.getElementById("2");
lsp.removeChild(lsp1)//调用父级删除
</script>
</html>
改
fn replaceChild(new,old) 需要父级来调用
fn setAttribute();
innerHTML代码示例
-
获取第一个类名为
item
的元素内容
document.querySelector('.box .item').innerHTML
练习:
<script>
var lsp = document.getElementById("wert");
var lsp1 = document.getElementById("2");
var lsp3 = document.createElement("p")
lsp3.innerHTML="那就一定会"
lsp.replaceChild(lsp3,lsp1)
</script>
查
querySelector()代码示例
-
获取被选择器
.box .item
匹配的第一个节点
document.querySelector('.box .item')
querySelectorAll()代码示例
//获取所以的li标签
var lis=document.querySelectorAll("li");
除了函数方法,我们还可以使用属性来获取节点信息,下表介绍了一些获取元素节点信息常用的属性。
名称 | 描述 |
---|---|
innerHTML | 返回元素内包含的所有HTML内容(文本和标签),类型为字符串 |
parentNode | 返回指定节点的父节点 |
children | 返回指定元素的子元素节点集合 |
firstElementChild | 返回指定元素的第一个子元素节点 |
lastElementChild | 返回指定元素的最后一个子元素节点 |
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<ul class="box">
<li class="item">
<span>海绵</span>
<button>确认</button>
</li>
<li class="item">
<span>hong</span>
<button>确认</button>
</li>
</ul>
<script>
var btn = document.querySelectorAll('button')
for (var idx = 0; idx < btn.length; idx++) {
btn[idx].addEventListener('click', function() {
this.parentNode.style.backgroundColor = 'blue'
})
}
</script>
</body>
</html>
结果:点击确认按钮把当前整行背景色设置为蓝色
parentNode代码示例
-
获取
input
元素节点的父节点
document.querySelector('input').parentNode
children代码示例
-
获取类名为
box
的元素的子节点集合
document.querySelector('.box').children
常用的节点属性获取方式
名称 | 描述 |
---|---|
getAttribute() | 返回元素一个指定的属性值 |
直接使用属性名称获取 | 适用于部分属性(如:title ,value ,href ) |
方式1 getAttribute()代码示例
-
获取input元素的value属性值
document.querySelector('input').getAttribute('value')
方式2 某些元素的属性值可以直接使用属性名获取
-
获取input元素的value属性值
document.querySelector('input').value
两种方式区别
-
方式1获取结果类型为String,方式2获取结果可以为不同类型
-
获取到的结果未必相同,如:a元素的href属性
-
属性有默认值时,方式1只能获取到初始默认值,方式2可以获取到实时更新的值,如:input元素的value属性
DOM控制CSS样式
1.通过style属性控制样式
style属性可以设置或返回元素的内联样式
-
语法:element.style.property = value
-
property为CSS属性名,如:color,margin。如果属性名原来包含“-”,则需转换为小驼峰形式,如:backgroundColor,marginLeft。
var box = document.querySelector('div')
box.style.color = "#fff" // 将元素中文字设置为白色
box.style.marginLeft = "100px" // 将元素左外边距设置为100px
2、通过classList控制样式
classList属性返回一个元素类属性集合(这里可以简单理解为类名的集合),通过使用classList中的方法可以方便的访问和控制元素类名,达到控制样式的目的
classList常用方法介绍
名称 | 描述 |
---|---|
add(class1, class2, …) | 添加一个或多个类名 |
remove(class1, class2, …) | 移除一个或多个类名 |
replace(oldClass, newClass) | 替换类名 |
contains(class) | 判定类名是否存在,返回布尔值 |
toggle(class, true|false) | 如果类名存在,则移除它,否则添加它,第二个参数代表无论类名是否存在,强制添加(true )或删除(false ) |
<div class="box">classList test</div>
<script>
var box = document.querySelector('.box')
box.classList.add('box1', 'box2') // [box] => [box, box1, box2]
box.classList.remove('box1', 'box2') // [box, box1, box2] => [box]
box.classList.replace('box', 'box2') // [box] => [box2]
box.classList.contains('box1') // 当前元素不包含类名box1,返回false
box.classList.toggle('active') // [box2] => [box2, active]
</script>
1、节点写入常用方式
名称 | 描述 |
---|---|
innerHTML | 返回元素中的html内容 ,通过赋值,可设置元素中的html内容 |
innerText | 返回元素中的文本内容,通过赋值,可设置元素中的文本内容 |
document.write() | 将html字符串 写入到文档中 |
节点写入
当我们需要更改一个标签的文字或内容时,这时就需要了解节点写入的知识,学会节点写入可以帮助我们更加精确的控制网页内容,节点写入的方式有很多种,这里介绍常用的几种方法。
1.1 innerHTML
-
在div中写入h1元素
<body>
<div></div>
</body>
<script>
document.querySelector('div').innerHTML = '<h1>我是新内容</h1>'
</script>
如果写入内容中包含html标签字符串,会被解析成对应的html标签
1.2 innerText
-
在div中写入字符串
<body>
<div></div>
</body>
<script>
document.querySelector('div').innerText = '<h1>我是新内容</h1>'
</script>
html标签字符串不会被解析,会被当作普通字符串写入
1.3 document.write()
document.write('我是新内容')
document.write('<h1>我是新内容</h1>')
和innerHTML类似,写入内容如果包含html标签字符串,会被解析成对应的html标签。document.write()根据运行时机,会写入文档不同的位置
案例
手风琴效果
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
html,body{
height:100%;
width: 100%;
background-size: cover;
background-position:center center;
position: relative;
background-color: blue;
background-image: url(../../img/海绵宝宝.jpeg);
}
ul{
width:800px;
height: 400px;
background-color: #21ea14;
/*万能居中公式*/
position: absolute;
left: 50%;
top: 50%;
margin-left:-400px;
margin-top: -200px;
}
li{
height: 400px;
width:80px;
float: left;
background-size: cover;
background-position: center center;
/*过度:当状态从某一个值变为另外一个值的时候所产生的时间*/
transition: .3s;
}
.open{
width: 480px;
}
li p{
width: 80px;
height: 400px;
background-color: rgba(255,255,255,.5);
color: #eaeaec;
font-size: 50px;
}
</style>
</head>
<body>
<ul>
<li class="open" style="background-image: url(../../img/海绵宝宝.jpeg);">
<p>海绵宝宝</p>
</li>
<li style="background-image: url(../../img/派大星.jpeg);">
<p>派大星</p>
</li>
<li style="background-image: url(../../img/珊迪.jpeg);">
<p>珊迪2</p>
</li>
<li style="background-image: url(../../img/蟹老板.jpeg);">
<p>蟹老板</p>
</li>
<li style="background-image: url(../../img/章鱼哥.jpeg);">
<p>章鱼哥</p>
</li>
</ul>
</body>
<script>
//获取所以的li标签
var lis=document.querySelectorAll("li");
//使用for遍历添加点击事件
for(var i=0;i<lis.length;i++){
lis[i].onclick=function () {
//收起展开的li
for(var j=0;j<lis.length;j++){
lis[j].className=""
}
//打开点击的li
this.className="open";
document.body.style.backgroundImage=this.style.backgroundImage;
}
}
</script>
</html>
选字游戏
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>选字游戏</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
font-family: simsun;
}
#wrap {
width: 420px;
margin: 0 auto;
position: relative;
min-height: 540px;
max-height: 640px;
border: 1px #ccc solid;
border-radius: 5px;
background: #dcdee0;
}
#time {
position: absolute;
left: 20px;
top: 20px;
font-size: 30px;
}
#wan {
position: absolute;
top: 20px;
right: 20px;
font-size: 30px;
}
#show {
font-size: 10em;
top: 90px;
left: 126px;
position: absolute;
}
#menu {
padding: 40px 30px;
font-size: 30px;
top: 250px;
position: absolute;
}
#ul1 {
position: absolute;
left: 10px;
bottom: 20px;
list-style: none;
}
#ul1 li {
float: left;
font-size: 5em;
}
</style>
</head>
<body>
<div id="wrap">
<div id="time">剩余时间:20</div>
<div id="wan">完成:0</div>
<div id="show">红</div>
<div id="menu">根据上面的字的颜色从下面选择正确的字,选择正确自动开始</div>
<ul id="ul1">
<li>绿</li>
<li>蓝</li>
<li>黑</li>
<li>黄</li>
<li>红</li>
</ul>
</div>
</body>
<script type="text/javascript">
var show = document.querySelector("#show"); //获取定义的元素
var lis = document.querySelectorAll("#ul1>li");
var menu = document.querySelector("#menu");
var wan = document.querySelector("#wan");
var time = document.querySelector("#time");
var score = 0;
var colorIndex = null;
var timeBol = false;
var count = 20;
var clickBol = true;
var colors = ["red", "yellow", "blue", "green", "black"];
var fonts = ["红", "黄", "蓝", "绿", "黑"];
function rand(min, max) {
return parseInt(Math.random() * (max - min + 1) + min);
}
function showRand() {
colorIndex = rand(0, 4);//candy
var fontIndex = rand(0, 4);
show.innerHTML = fonts[fontIndex];
show.style.color = colors[colorIndex];
}
function grade() {
if (score <= 2) {
alert("你是色盲ma");
} else if (score < 5) {
alert("你是色弱嘛");
} else if (score < 10) {
alert("一般");
} else if (score < 15) {
alert("表现不错");
}
}
function createArr() {
var arr = [];
while (arr.length < 5) {
var r = rand(0, 4);
for (var j = 0; j < arr.length; j++) {
if (arr[j] == r) { //除掉重复的字
break;
}
}
if (j == arr.length) {
arr.push(r);
}
}
// alert(arr);
return arr;
}
function textRand() {
var colorArr = createArr();//存储的就是每个li颜色的下标值
console.log(colorArr);
var fontArr = createArr();
for (var i = 0; i < lis.length; i++) {
lis[i].innerHTML = fonts[fontArr[i]];
lis[i].style.color = colors[colorArr[i]];
lis[i].fontIndex = fontArr[i];
}
}
//循环时间的函数
var timer = setInterval(function () {
if (timeBol) {
count--;
if (count <= 0) {
clearInterval(timer); //每次条用的时候清0一下
clickBol = false;
grade();
}
time.innerHTML = "剩余时间:" + count;
}
}, 1000);
showRand();
textRand();
for (var i = 0; i < lis.length; i++) {
lis[i].onclick = function () {
if (colorIndex == this.fontIndex && clickBol) {
// alert("点对了");
menu.style.display = "none";
showRand();
textRand();
score++;
timeBol = true;
// timeBol=true;
wan.innerHTML = "完成:" + score;
}
}
}
</script>
</html>