Learn more about JavaScript's DOM
通过HTML DOM,可访问JavaScript HTML文档的所有元素。下面本篇文章就来给大家介绍一下,有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
DOM能干啥?
● JavaScript 能够改变页面中的所有 HTML 元素
● JavaScript 能够改变页面中的所有 HTML 属性
● JavaScript 能够改变页面中的所有 CSS 样式
● JavaScript 能够对页面中的所有事件做出反应
【相关课程推荐:JavaScript视频教程】
当网页被加载时,浏览器会创建页面的文档对象模型(Document Object Model)。
HTML DOM 模型被构造为对象的树:
查找元素方法:
1、直接查找:
● getElementByid(): 通过 id 找到 HTML 元素
● getElementsByTagName(): 通过标签名找到 HTML 元素(列表)
● getElementsByClassName(): 通过类名找到 HTML 元素(列表)
● getelementsByName(): 通过name属性找到HTML元素(列表)
2、间接查找:
parentNode 父节点 childNodes 所有子节点 firstChild 第一个子节点 lastChild 最后一个子节点 nextSibling 下一个兄弟节点 previousSibling 上一个兄弟节点 parentElement 父节点标签元素 children 所有子标签 firstElementChild 第一个子标签元素 lastElementChild 最后一个子标签元素 nextElementtSibling 下一个兄弟标签元素 previousElementSibling 上一个兄弟标签元素
3、添加删除节点和元素:
操作方法:
innerText 文本,指定ID下所有文本的拼接,去除间隔的HTML元素 outerText 写模式下,替换所有子元素 innerHTML 会根据指定的值创建新的 DOM 树,然后用这个 DOM 树完全替换调用元素原先的所有子节点。 outerHTML 写模式下,新的元素替换原有的 DOM 树 value 属性可设置或返回密码域的默认值。获取文本框的值。
Class属性操作(CSS样式表名):
className 获取所有类名 classList.remove(cls) 删除指定类 classList.add(cls) 添加类
checkbox属性:
checkbox.checked:true选中,false不选
tag标签操作:
1、createElement()创建标签:
每个HTML标签都有自己的属性,属性参照:https://www.w3school.com.cn/jsref/dom_obj_anchor.asp
function append_tag(){ var a = document.createElement('a') var cur = document.getElementById('dd') a.innerHTML='click me' a.href='http://www.baidu.com' a.className='a1' cur.appendChild(a) //添加标签}\\----------等同于 var a_tag="<a class='a1' href='>click me</a>"
2、操作标签:
insertAdjacentText('位置',obj) 在指定的地方插入文本内容,如果是HTML对象会以文本形式显示出来
insertAdjacentHTML('位置',obj) 在指定的地方插入html内容
位置说明:
beforeBegin:标签起始位置前(标签前) afterBegin:标签起始位置后(标签内) beforeEnd:标签结束位置前(标签内) afterEnd: 标签结束位置后(标签外)
3、标签样式操作style:
var obj = document.getElementById('i1') obj.style.fontSize = "32px"; obj.style.backgroundColor = "red";
4、位置操作
document.documentElement.offsetHeight 总文档高度 document.documentElement.clientHeight 当前文档占屏幕高度 tag.offsetHeight 自身高度 tag.offsetTop 距离上级定位高度 tag.offsetParent 父定位标签 tag.scrollTop 滚动高度
/* clientHeight -> 可见区域:height + padding clientTop -> border高度 offsetHeight -> 可见区域:height + padding + border offsetTop -> 上级定位标签的高度 scrollHeight -> 全文高:height + padding scrollTop -> 滚动高度 特别的: document.documentElement代指文档根节点 */
事件:
addEventListener() 方法用于向指定元素添加事件句柄。
addEventListener() 方法添加的事件句柄不会覆盖已存在的事件句柄。
你可以向一个元素添加多个事件句柄。
你可以向同个元素添加多个同类型的事件句柄,如:两个 "click" 事件。
你可以向任何 DOM 对象添加事件监听,不仅仅是 HTML 元素。如: window 对象。
addEventListener() 方法可以更简单的控制事件(冒泡与捕获)。
当你使用 addEventListener() 方法时, JavaScript 从 HTML 标记中分离开来,可读性更强, 在没有控制HTML标记时也可以添加事件监听。
你可以使用 removeEventListener() 方法来移除事件的监听。
语法:
element.addEventListener(event, function, useCapture);
事件类型:
Properties | When did this event occur... | Properties | When did this event occur ... |
---|---|---|---|
onabort | The loading of the image was interrupted. | onload | A page or image is loaded. |
onblur | The element loses focus. | onmousedown | The mouse button is pressed. |
onchange | The content of the field is changed. | onmousemove | The mouse was moved. |
onclick | Event handler called when the user clicks on an object. | onmouseout | The mouse moves away from an element. |
ondblclick | Event handler called when the user double-clicks an object. | onmouseover | Move the mouse over an element. |
onerror | An error occurred while loading the document or image. | onmouseup | The mouse button was released. |
onfocus | The element gets focus. | onreset | The reset button is clicked. |
onkeydown | A certain keyboard key was pressed. | onresize | The window or frame was resized. |
onkeypress | A keyboard key is pressed and released. | onselect | The text is selected. |
onkeyup | A certain keyboard key was released. | onsubmit | The confirmation button is clicked. |
onunload | The user exits the page. |
键盘鼠标事件:
属性 | 描述 |
---|---|
altKey | 返回当事件被触发时,"ALT" 是否被按下。 |
button | 返回当事件被触发时,哪个鼠标按钮被点击。 |
clientX | 返回当事件被触发时,鼠标指针的水平坐标。 |
clientY | 返回当事件被触发时,鼠标指针的垂直坐标。 |
ctrlKey | 返回当事件被触发时,"CTRL" 键是否被按下。 |
metaKey | 返回当事件被触发时,"meta" 键是否被按下。 |
relatedTarget | 返回与事件的目标节点相关的节点。 |
screenX | 返回当某个事件被触发时,鼠标指针的水平坐标。 |
screenY | 返回当某个事件被触发时,鼠标指针的垂直坐标。 |
shiftKey | 返回当事件被触发时,"SHIFT" 键是否被按下。 |
小例子:
1、文本框默认文字
<input id="i1" type="text" onfocus="foucs(this)" onblur="blurs(this)" value="请输入关键字"/> <script> function foucs(th){ var v=th.value; if (v=='请输入关键字'){ th.value=''; } } function blurs(th){ var v=th.value; if (v.length==0){ th.value='请输入关键字'; th.style.color="gray"; th.style.border="1px solid red"; } }</script>
2、添加标签
<div style="border: 1px solid red;" id="std"></div> function b_b(){ var std=document.getElementById('std'); var new_b="<input type='button' value='我是beforeBegin,在DIV前' />"; std.insertAdjacentHTML('beforeBegin',new_b);} function a_b(){ var std=document.getElementById('std'); var new_b="<input type='button' value='我是afterBegin,在DIV内前' />"; std.insertAdjacentHTML('afterBegin',new_b);} function b_e(){ var std=document.getElementById('std'); var new_b="<input type='button' value='我是beforeEnd,在DIV后' />"; std.insertAdjacentHTML('beforeEnd',new_b);} function a_e(){ var std=document.getElementById('std'); var new_b="<input type='button' value='我是afterEnd,在DIV内后'/>"; std.insertAdjacentHTML('afterEnd',new_b);}
3、展开同时隐藏其它子菜单:
HTML:
<div id="left_menu" class="left_menu"> <div id='m1' class="main_menu" onclick="show_sub_menu(this)"><span>人员管理</span></div> <div id='sm1' class="sub_menu"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> </ul> </div> <div id='m2' class="main_menu" onclick="show_sub_menu(this)"><span>组别管理</span></div> <div id='sm2' class="sub_menu"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> <li>6</li> <li>7</li> </ul> </div></div>
js:
function show_sub_menu(th){ var parentId = th.id; var childId='s'+parentId; var childE=document.getElementById('left_menu').children; for (var s in childE){ var e=childE[s].classList; console.log(e); if (e){ if (childE[s].id==childId){ childE[s].classList.add('show'); }else{ childE[s].classList.remove('show'); } } }}
4、标签提交:
<!-- DOM提交标单!--><form id="f1" action="search.html"> <input id="input1" type="text"/> <a onclick="a_submit()">提交吧</a></form><script> function a_submit(){ document.getElementById('f1').submit(); }</script>
5、html、css、js页面分离:生产环境的写法。
每类存储为单独的文件,其中js使用dom添加事件方法,可以html更简洁。
例子:鼠标移动表格行变色
HTML:
<table id='tb'> <tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr> <tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr> <tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr> <tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr> <tr><td>1</td><td>1</td><td>1</td><td>1</td><td>1</td></tr></table>
JS:给table添加属性和class
var t=document.getElementById('tb').classList; t.add('tb_style'); var mytrs=document.getElementsByTagName('tr'); var td_numbers=mytrs.length; for (var td=0;td<td_numbers;td++){ mytrs[td].onmouseover=function(){this.style.backgroundColor='red';}; mytrs[td].onmouseout=function(){this.style.backgroundColor='';}; }
css
.tb_style{ bacground-color:pink;}
6、词法分析:形参--》函数体内函数,编译时函数体内的函数会分配 内存地址,覆盖形参。
function cifa(age){ console.log(age); \\function age age=22; console.log(age); \\22 function age(){}; console.log(age); \\22}age(3)
The above is the detailed content of Learn more about JavaScript's DOM. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
