表单元素获取,dom树的遍历与常用属性,dom元素的增删改, js操作元素内容,留言板实例,dataset对象,获取元素计算样式,classList 对象常用方法 ,事件的添加与派发
发布于:2022-01-09 11:17:32
次阅读
获取表单元素
- document.forms: 获取页面所有表单
- form.id: 获取元素
- form.id.name: 获取元素
- form.id.name.value: 获取元素值
<!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>获取表单元素</title> <style> .login { width: 15em; border: 1px solid #888; border-radius: 0.5em; box-shadow: 5px 5px 5px #888; display: grid; grid-template-columns: 3em 1fr; gap: 0.5em 1em; } .login legend { padding: 0 0.5em; text-align: center; margin-bottom: 0.5em; font-weight: bolder; } .login button { grid-column: 2; } .login button:hover { cursor: pointer; background-color: lightcyan; } </style> </head> <body> <form action="login.php" method="post" id="login"> <fieldset class="login"> <legend>请登录</legend> <label for="email">邮箱:</label> <input type="email" name="email" id="email" value="help_10086@foxmail.com" autofocus /> <label for="password">密码:</label> <input type="password" name="password" id="password" value="zh10086" /> <button>提交</button> </fieldset> </form> <script> // 获取表单元素方式 // console.log(document.forms[0]); // form.id // console.log(document.forms.login); // input:name,此时 name 相当于 id // console.log(document.forms.login.email); // value // console.log(document.forms.login.email.value); // 前后端数据交互, json let login = document.forms.login; let email = login.email.value; let password = login.password.value; console.log(email, password); // let user = { email: email, password: password }; let user = { email, password }; // 提交到服务器端/后端: json let data = JSON.stringify(user, null, 2); console.log(data); </script> </body></html>

dom 树的遍历与常用属性
- 节点类型:元素, 文本, 属性, 注释,文档…,通常只关注元素类型
- 类数组: “类似”数组,像数组,但不是真正的数组,所以不能用数组上的方法类数组特征:
- 具有从 0 开始递增的正整数索引
- 具有 length 属性, 表示成员数量
let list = document.querySelector(".list");// childNodes 所有类型元素console.log(list.childNodes);// children 元素类型元素console.log(list.children);// 类数组 ==> 真数组// 2.1 Array.from()console.log(Array.from(list.children));// 2.2 ...restconsole.log([...list.children]);
dom 树的遍历
| stt |
语法 |
说明 |
| 1 |
firstElementChild |
第一个 |
| 2 |
nextElementSibling |
下一个 |
| 3 |
lastElementChild |
最后一个 |
| 4 |
previousElementSibling |
前一个 |
| 5 |
parentElment / parentNode |
父节点 |
<body> <div class="list"> <div class="item">item1</div> <div class="item">item2</div> <div class="item">item3</div> <div class="item">item4</div> <div class="item">item5</div> <div class="item">item6</div> </div></body><script> // 1. 节点类型:元素, 文本, 属性, 注释,文档... // 通常只关注元素类型 let list = document.querySelector(".list"); // childNodes 所有类型元素 console.log(list.childNodes); // children 元素类型元素 console.log(list.children); // 2. 类数组: "类似"数组,像数组,但不是真正的数组,所以不能用数组上的方法 // 类数组特征: // 1. 具有从0开始递增的正整数索引 // 2. 具有length属性, 表示成员数量 // 类数组 ==> 真数组 // 2.1 Array.from() console.log(Array.from(list.children)); // 2.2 ...rest console.log([...list.children]); // 3. 遍历 //第一个, firstElementChild console.log([...list.children][0]); [...list.children][0].style.color = "blue"; list.firstElementChild.style.background = "yellow"; // 下一个兄弟, 第2个, nextElementSibling list.firstElementChild.nextElementSibling.style.background = "green"; // 最后一个, lastElementChild list.lastElementChild.style.background = "yellow"; // 前一个兄弟, previousElementSibling list.lastElementChild.previousElementSibling.style.background = "lightgreen"; // 父节点/元素节点, parentElment / parentNode // ul.lastElementChild.parentElement.style.border = "4px solid"; list.lastElementChild.parentNode.style.border = "4px solid red";</script>
DOM 元素的增删改操作
- outerHTML: 元素的 html 字符串表示
- cloneNode(true): 克隆节点, true, 复制元素后代的内容
插入元素
| STT |
语法 |
说明 |
| 1 |
document.createElement("ul") |
创建 ul 元素 |
| 2 |
document.body.append(ul) |
在 body 中添加 ul 元素 |
| 3 |
three.before(li) |
在 three 元素节点前插入 li |
| 4 |
three.after(cloneLi) |
在 three 元素节点后插入克隆 li |
| 5 |
insertAdjacentElement |
在父节点的标签为插入点,进行插入元素 |
- insertAdjacentElement: 在父节点的标签为插入点,进行插入元素
- insertAdjacentElement(‘插入位置’, 元素)
afterBegin: 开始标签之后,第一个子元素beforeBegin: 开始标签之前,是它的前一个兄弟元素afterEnd: 结束标签之后,它的下一个兄弟元素beforeEnd: 结束标签之前,它的最后一个子元素
替换元素:.replaceChild
- ul.replaceChild(‘替换元素’, ‘被替换元素’);
删除元素:.remove
- ul.lastElementChild.remove();
<script> // 1. 创建元素,document 文档对象 const ul = document.createElement("ul"); // 2. 添加到页面中/html中: append document.body.append(ul); // 3. 为ul列表添加元素 for (let i = 0; i < 5; i++) { const li = document.createElement("li"); li.textContent = "item" + (i + 1); ul.append(li); } // 4.查看元素 console.log(ul); // outerHTML: 元素的html字符串表示 console.log(ul.outerHTML); // 5. 在节点之前插入: before const li = document.createElement("li"); li.textContent = "new item"; li.style.color = "red"; const three = document.querySelector("ul li:nth-of-type(3)"); three.before(li); // 6. 在节点之后插入 : after // cloneNode(true): 克隆节点, true, 复制元素后代的内容 let cloneLi = li.cloneNode(true); three.after(cloneLi); // 7. 在父节点的标签为插入点,进行插入元素 // insertAdjacentElement('插入位置', 元素) // 插入位置有四个 // afterBegin: 开始标签之后,第一个子元素 // beforeBegin: 开始标签之前,是它的前一个兄弟元素 // afterEnd: 结束标签之后,它的下一个兄弟元素 // beforeEnd: 结束标签之前,它的最后一个子元素 ul.style.border = "1px solid"; const h3 = document.createElement("h3"); h3.textContent = "商品列表"; ul.insertAdjacentElement("beforeBegin", h3); const p = document.createElement("p"); p.textContent = "共计: 7 件"; ul.insertAdjacentElement("afterEnd", p); // 8. 替换 replaceChild // 1. 插入点 const last = document.querySelector("ul li:last-of-type"); // 2. 插入的元素 const a = document.createElement("a"); a.href = "https://php.cn"; a.textContent = "php.cn"; // 3. 执行替换 ul.replaceChild(a, last); // 9. 移除: remove ul.lastElementChild.remove(); </script>
JS 操作元素内容的常用方法与异同
- innerHTML: 可解析 html 字符, innerText: 不解析 html 字符
|
|
|
|
textContent |
返回元素以及后代元素中的所有文本内容 |
|
innerText |
返回元素以及后代中的文本 |
|
innerHTML |
返回内部的 html 字符串 |
|
outerHTML |
返回当前节点的自身的 html 字符串 |
|
.outerHTML = url; |
替换 |
|
.outerHTML = none; |
清空 |
<script> const box = document.querySelector(".box"); // textContent: 返回元素以及后代元素中的所有文本内容,包括 <style>, display:none的内容 console.log(box.textContent); // innerText: 返回元素以及后代中的文本 console.log(box.innerText); // innerHTML: 返回内部的html字符串 console.log(box.innerHTML); // textContent, innerText ? textContent 首选, innerText,2016才成为w3c标准 // innerText, innerHTML 区别? let p = document.createElement("p"); let url = '<a href="https://php.cn">php.cn</a>'; p.innerText = url; box.append(p); p = document.createElement("p"); p.innerHTML = url; box.append(p); // innerHTML: 可解析html字符, innerText: 不解析html字符 // outerHTML: 返回当前节点的自身的html字符串 console.log(box.outerHTML); // 替换 // box.outerHTML = url; // 清空/删除 box.outerHTML = null; </script>
留言板实例
<!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>留言板实战</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; } .content{ margin: 20px 80px; display: flex; flex-direction: column; width: 460px; } .content > input{ height: 38px; margin-bottom: 18px; font-size: 1.2rem; } .content > ul{ margin-left: 13px; } .content > ul li{ margin-right: 13px; } .content > ul > li > button{ background-color: #85f0f8; margin-left: 13px; } </style> </head> <body> <div class="content"> <!-- onkeydown: 按下键时触发 --> <input type="text" onkeydown="addMsg(this)" placeholder="请输入留言内容" autofocus /> <ul class="list"></ul> </div> <script> function addMsg(ele) { console.log(ele); // event:保存了当前所有的事件信息,是当前事件的事件对象 // event: 在事件方法中, 总是可用的 console.log(event); console.log(event.key); if (event.key === "Enter") { // 1. 获取留言列表的容器 const ul = document.querySelector(".list"); // 2. 判断留言是否为空? if (ele.value.length === 0) { alert("留言内容不能为空"); ele.focus(); return false; } // 3. 添加一条新留言 const li = document.createElement("li"); // li.textContent = ele.value; // ul.append(li); // before // ul.firstElementChild.before(li); // 插入到起始标签的后面就永远是第一条 // 添加删除留言功能 li.innerHTML = ele.value + "<button onclick='del(this.parentNode)'>删除</button>"; ul.insertAdjacentElement("afterBegin", li); // 4. 清空留言的输入框,为下一次做准备 ele.value = null; // 5. 重置焦点到留言框中,方便用户更次输入 ele.focus(); } } // 删除功能 function del(ele) { return confirm("是否删除?") ? ele.remove() : false; } </script> </body></html>
dataset 对象
- 元素属性有二类:
- 内置的预定义属性, 如 id, class,title,style 等
- 用户自定义属性,主要用于 js 脚本控制, 以 “data-“”为前缀,如 data-key
- 自定义属性还可以将一些数据保存到标签中
<!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>自定义属性: dataset对象</title> </head> <body> <!-- * 元素属性有二类: * 1. 内置的预定义属性, 如 id, class,title,style等 * 2. 用户自定义属性,主要用于js脚本控制, 以 "data-""为前缀,如 data-key --> <div class="btn-group"> <!-- onclick: 内置/预定义事件属性 --> <!-- data-index: 自定义属性 --> <button data-index="1" onclick="getIndex(this)">btn1</button> <button data-index="2" onclick="getIndex(this)">btn2</button> <button data-index="3" onclick="getIndex(this)">btn3</button> </div> <!-- 自定义属性还可以将一些数据保存到标签中 --> <!-- data-emial, data-work-unit --> <div class="user" data-email="498668472@qq.com" data-work-unit="php中文网">猪老师</div> <script> function getIndex(btn) { // 通过自定义属性data-index的值,知道我点的是哪一个? // dataset.prop, "data-"一定要省略掉 console.log("点击了第 ", btn.dataset.index, " 个按钮"); } const user = document.querySelector(".user"); console.log(user.dataset.email); // work-unit ==> workUnit console.log(user.dataset.workUnit); // dataset 可读可写 user.dataset.workUnit = "php.cn"; console.log(user.dataset.workUnit); </script> </body></html>
获取元素的计算样式
<!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>JS操作CSS</title> <style> div { width: 150px; height: 100px; } </style> </head> <body> <div style="color: #ff009d; background-color: #e7ebe7">Help_10086</div> <script> const div = document.querySelector("div"); // 行内样式,style console.log(div.style.color); console.log(div.style.backgroundColor); // console.log(div.style.width); // console.log(div.style.height); // 计算样式: 内部<style>或外部 如 style.css console.log(window.getComputedStyle(div).width); console.log(window.getComputedStyle(div).height); console.log(window.getComputedStyle(div).backgroundColor); const width = window.getComputedStyle(div).width; console.log(width, typeof width); // 150px ===> 150 console.log(typeof parseInt(width)); div.style.width = parseInt(width) + 100 + "px"; </script> </body></html>
classList 对象常用方法
<!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>JS操作class属性: classList对象</title> <style> .red { color: red; } .bgc { background-color: yellow; } .blue { color: blue; } .bd { border: 5px solid #686464; } </style> </head> <body> <h2>Help_10086</h2> <script> // 1.传统方式 const h2 = document.querySelector("h2"); // h2.className = "red bgc"; // 2. classList对象 // add: 添加class h2.classList.add("red"); h2.classList.add("bgc"); // contains: 判断是否存在 console.log(h2.classList.contains("bgc")); // remove: 移除class h2.classList.remove("bgc"); // replace: 替换class h2.classList.replace("red", "blue"); // toggle: 切换 class // 如果已存在 bd, 则执行remove 移除操作, 否则执行 add 添加操作 h2.classList.toggle("bd"); </script> </body></html>
事件的添加与派发
<!DOCTYPE html><html lang="zh-CN"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>事件的添加与删除</title> </head> <body> <button>元素对象</button> <button>元素事件监听器</button> <button>事件派发/点击广告赚钱</button> <script> const btn1 = document.querySelector("button:first-of-type"); // 添加 btn1.onclick = function () { console.log(event); }; // 删除事件 btn1.onclick = null; // 事件监听器 const btn2 = document.querySelector("button:nth-of-type(2)"); function show() { console.log(event); } // 事件回调方法不能移除,必须是命名函数才可以 btn2.addEventListener("click", show, false); btn2.removeEventListener("click", show, false); // 事件派发 const btn3 = document.querySelector("button:nth-of-type(3)"); // 先添加一个事件,然后自动去的触发它 let i = 0; btn3.addEventListener( "click", () => { console.log("恭喜你,又赚了 : " + i + "元"); i += 0.8; }, false ); // 创建一个自定义事件 const myclick = new Event("click"); // btn3.dispatchEvent(myclick); // btn3.dispatchEvent(myclick); // btn3.dispatchEvent(myclick); // btn3.dispatchEvent(myclick); // btn3.dispatchEvent(myclick); // btn3.dispatchEvent(myclick); // setTimeout()一次性定时器 // setTimeout(() => btn3.dispatchEvent(myclick), 2000); // setInterval: 间歇式的定时器,不停重复执行 setInterval(() => btn3.dispatchEvent(myclick), 2000); </script> </body></html>