文档对象模型dom_什么是文档对象模型,以及为什么应该知道如何使用它。

文档对象模型dom

by Leonardo Maldonado

莱昂纳多·马尔多纳多(Leonardo Maldonado)

什么是文档对象模型,以及为什么应该知道如何使用它。 (What’s the Document Object Model, and why you should know how to use it.)

So, you’ve studied HTML, you’ve created your first tags, learned about CSS, made beautiful forms, amazing buttons, responsive pages and have started to show everyone how amazing all that was.

因此,您学习了HTML,创建了第一个标签,了解了CSS,制作了精美的表格,使用了令人惊叹的按钮,并创建了响应式页面,并开始向所有人展示这一切的惊人之处。

But then you decide that you want to take another step in your learning, and you’ve started wonder to yourself: “How can I add animation to my page? I wish that button made some animation on my page when I clicked it!”

但是随后您决定要进一步学习,就开始对自己产生疑问:“如何向页面添加动画? 我希望当我单击该按钮时,该按钮在页面上产生一些动画效果!”

Well, that’s where the DOM comes to solve your problem. You’ve probably heard a lot about it, but you might not know yet what is it and what problems it solves. So let’s dig in.

嗯,这就是DOM解决您问题的地方。 您可能已经听说了很多,但是您可能还不知道它是什么以及它解决了什么问题。 因此,让我们深入。

那么,什么是DOM? (So, what’s the DOM?)

Do you know all those cool animations that you see around, that make you think to yourself, “Wow, I wish I could make something like that”? All of those animations are made by manipulating the DOM. I will now explain to you how to start manipulating it and making your websites look cooler.

您是否知道周围出现的所有很棒的动画,这些动画会让您自己想:“哇,我希望我能做出类似的事情”? 所有这些动画都是通过操纵DOM制作的。 现在,我将向您解释如何开始操作它并使您的网站看起来更酷。

The DOM (Document Object Model) is an interface that represents how your HTML and XML documents are read by the browser. It allows a language (JavaScript) to manipulate, structure, and style your website. After the browser reads your HTML document, it creates a representational tree called the Document Object Model and defines how that tree can be accessed.

DOM(文档对象模型)是一个界面,表示浏览器如何读取HTML和XML文档。 它允许使用一种语言(JavaScript)来操纵,构建和设置网站样式。 浏览器读取HTML文档后,它将创建一个称为“文档对象模型”的代表性树,并定义如何访问该树。

优点 (Advantages)

By manipulating the DOM, you have infinite possibilities. You can create applications that update the data of the page without needing a refresh. Also, you can create applications that are customizable by the user and then change the layout of the page without a refresh. You can drag, move, and delete elements.

通过操作DOM,您将拥有无限的可能性。 您可以创建无需刷新即可更新页面数据的应用程序。 另外,您可以创建用户可自定义的应用程序,然后无需刷新即可更改页面的布局。 您可以拖动,移动和删除元素。

As I said, you have infinite possibilities — you just need to use your creativity.

正如我所说,您拥有无限的可能性-您只需要发挥创造力即可。

浏览器表示 (Representation by the browser)

In the image above, we can see the representational tree and how it is created by the browser. In this example, we have four important elements that you’re gonna see a lot:

在上图中,我们可以看到代表性树以及浏览器如何创建它。 在此示例中,我们将看到四个重要的元素:

  1. Document: It treats all the HTML documents.

    Document :处理所有HTML文档。

  2. Elements: All the tags that are inside your HTML or XML turn into a DOM element.

    元素HTMLXML内的所有标签都将变成DOM元素。

  3. Text: All the tags’ content.

    文字 :所有标签的内容。

  4. Attributes: All the attributes from a specific HTML element. In the image, the attribute class=”hero” is an attribute from the <p> element.

    属性 :来自特定HTML元素的所有属性。 在图像中,属性class =“ hero”< p>元素的属性。

操作DOM (Manipulating the DOM)

Now we’re getting to the best part: starting to manipulate the DOM. First, we’re gonna create an HTML element as an example to see some methods and how events work.

现在,我们进入了最好的部分:开始操作DOM。 首先,我们将创建一个HTML元素作为示例,以了解一些方法以及事件如何工作。

<!DOCTYPE html>  <html lang="pt-br">  <head>      <meta charset="UTF-8">      <meta name="viewport" content="width=device-width, initial-scale=1.0">      <meta http-equiv="X-UA-Compatible" content="ie=edge">      <title>Entendendo o DOM (Document Object Model)</title>  </head>  <body>      <div class="container">          <h1><time>00:00:00</time></h1>          <button id="start">Start</button>          <button id="stop">Stop</button>          <button id="reset">Reset</button>      </div>  </body>  </html>

Very simple, right? Now we’re going to learn more about DOM methods: how to get our elements and start manipulating.

很简单,对吧? 现在,我们将学习有关DOM方法的更多信息:如何获取元素并开始进行操作。

方法 (Methods)

The DOM has a lot of methods. They are the connection between our nodes (elements) and events, something that we’ll learn more about later. I’m gonna show you some of the most important methods and how they’re used. There are a lot more methods that I’m not going to show you here, but you can see all of them methods here.

DOM有很多方法。 它们是节点(元素)和事件之间的连接,我们稍后将详细了解。 我将向您展示一些最重要的方法以及它们的用法。 有很多更多的方法,我不是要你在这里展示,但你可以看到所有的这些方法在这里 。

getElementById() (getElementById())

This method returns the element that contains the name id passed. As we know, id’s should be unique, so it’s a very helpful method to get only the element you want.

此方法返回包含传递的名称ID的元素。 众所周知, id应该是唯一的,因此这是仅获取所需元素的非常有用的方法。

var myStart = document.getElementsById('start');

myStart: Our variable name that looks similar to our id passed.

myStart :类似于我们传递的id的变量名。

start: id passed. And in case we do not have any id with that specific name, it returns null.

开始id已通过。 如果我们没有该特定名称的ID ,它会返回null

getElementsByClassName() (getElementsByClassName())

This method returns an HTMLCollection of all those elements containing the specific name class passed.

此方法返回所有包含传递的特定名称类的元素的HTMLCollection

var myContainer = document.getElementsByClassName('container');

myContainer: Our variable name that looks similar to our class passed.

myContainer :我们的变量名称,看起来与传递的相似。

.container: our class passed. In case we do not have any class with that specific name, it returns null.

.container :我们班级通过。 如果我们没有任何具有该特定名称的 ,则它返回null

getElementsByTagName() (getElementsByTagName())

This works the same way as those methods above: it also returns an HTMLCollection, but this time with a single difference: it returns all those elements with the tag name passed.

这与上述方法的工作方式相同:它还返回HTMLCollection,但是这次只是一个不同:它返回所有带有已传递标签名称的元素

var buttons = document.getElementsByTagName('button');

buttons: Our variable name that looks similar to our tag name passed.

button :我们的变量名,看起来与传递的标签名相似。

button: tag name that we want to get.

button :我们要获取的标签名称

querySelector() (querySelector())

It returns the first element that has the specific CSS selector passed. Just remember that the selector should follow the CSS syntax. In case you do not have any selector, it returns null.

它返回传递了特定CSS选择器的第一个元素 。 请记住, 选择器应遵循CSS语法 。 如果没有任何选择器 ,它将返回null

var resetButton = document.querySelector('#reset');

resetButton: Our variable name that looks similar to our selector passed.

resetButton :我们的变量名看起来与传递的选择器相似。

#reset: selector passed, and if you don’t have any selector that matches it returns null.

#reset选择器已传递,如果没有与之匹配的选择器 ,则返回null

querySelectorAll() (querySelectorAll())

Very similar to the querySelector() method, but with a single difference: it returns all the elements that match with the CSS selector passed. The selector should also follow the CSS syntax. In case you do not have any selector, it returns null.

querySelector()方法非常相似,但有一个区别:它返回与传递的CSS选择器匹配的所有元素选择器还应遵循CSS语法 。 如果没有选择器 ,则返回null

var myButtons = document.querySelector('#buttons');

myButtons: Our variable name that looks similar to our selectors passed.

myButtons :看起来与传递的选择器相似的变量名。

#buttons: selector passed, if you don’t have any selector that matches it returns null.

#buttons :通过选择器 ,如果没有与之匹配的选择器 ,则返回null

Those are some the most used DOM methods. There are several more methods that you can use, like the createElement(), which creates a new element in your HTML page, and setAttribute() that lets you set new attributes for elements HTML. You can explore them on your own.

这些是最常用的DOM方法。 还有其他几种方法可以使用,例如createElement()在HTML页面中创建一个新元素,以及setAttribute(),用于为HTML元素设置新属性。 您可以自己探索它们。

Again, you can find all the methods here, on the left side in Methods. I really recommend you take a look at some of the others because you might need one of them sometime soon.

同样,您可以在“方法”左侧的此处找到所有方法 。 我真的建议您看看其他一些,因为您可能很快就会需要其中一些。

Now, we’re going to learn about Events — after all without them we can’t make animations in our pages.

现在,我们将学习事件 -毕竟,如果没有事件 ,我们将无法在页面中制作动画。

大事记 (Events)

The DOM elements have methods, as we just discussed, but they also have events. These events are responsible for make interactivity possible in our page. But here’s one thing that you might not know: events are also methods.

就像我们刚刚讨论的那样,DOM元素具有方法 ,但是它们也具有事件 。 这些事件负责使我们页面中的交互成为可能。 但是,您可能不知道这件事: 事件也是方法

点击 (click)

One of the most used events is the click event. When the user clicks on a specific element, it will realize some action.

点击事件是最常用的事件之一。 当用户单击特定元素时,它将实现一些操作。

myStart.addEventListener('click', function(event) {
// Do something here.
}, false);

The addEventListener() parameters are:

addEventListener()参数为:

  1. The type of the event that you want (in this case ‘click’).

    所需事件的类型(在这种情况下为“ 单击 ”)。

  2. A callback function

    回调函数
  3. The useCapture by default is false. It indicates whether or not you want to “capture” the event.

    默认情况下, useCapture为false。 它指示您是否要“捕获”事件。

选择 (select)

This events is for when you want to dispatch something when a specific element is selected. In that case we’re gonna dispatch a simple alert.

当选择特定元素时要分派某些东西时,将使用此事件。 在这种情况下,我们将发出一个简单的警报

myStart.addEventListener('select', function(event) {
alert('Element selected!');
}, false);

These are some of the most commonly used events. Of course, we have a lot of other events that you can use, like drag & drop events — when a user starts to drag some element you can make some action, and when they drop that element you can make another action.

这些是一些最常用的事件。 当然,我们还有许多其他事件可以使用,例如拖放事件-当用户开始拖动某个元素时,您可以执行某些操作,而当用户拖放该元素时,您可以执行另一个操作。

Now, we’re gonna see how we can traverse the DOM and use some properties.

现在,我们将看到如何遍历DOM并使用一些属性。

遍历DOM (Traversing the DOM)

You can traverse the DOM and use some properties that we’re gonna see now. With these properties, you can return elements, comments, text, and so on.

您可以遍历DOM并使用我们现在要看到的一些属性。 使用这些属性,您可以返回元素,注释,文本等。

.childNodes (.childNodes)

This property returns a nodeList of child nodes of the given element. It returns text, comments, and so on. So, when you want to use it, you should be careful.

此属性返回给定元素的子节点nodeList 。 它返回文本,注释等。 因此,当您要使用它时,应该小心。

var container = document.querySelector('.container');
var getContainerChilds = container.childNodes;

。第一个孩子 (.firstChild)

This property returns the first child of the given element.

此属性返回给定元素的第一个孩子。

var container = document.querySelector('.container');
var getFirstChild = container.firstChild;

.nodeName (.nodeName)

This property returns the name of the given element. In this case, we passed a div, so it will return “div”.

此属性返回给定元素的名称。 在这种情况下,我们传递了一个div ,因此它将返回“ div ”。

var container = document.querySelector('.container');
var getName = container.nodeName;

.nodeValue (.nodeValue)

This property is specific for texts and comments, as it returns or sets the value of the current node. In this case, since we passed a div, it will return null.

此属性特定于文本和注释 ,因为它返回或设置当前节点的值。 在这种情况下,由于我们传递了div,因此它将返回null

var container = document.querySelector('.container')
var getValue = container.nodeValue;

.nodeType (.nodeType)

This property returns the type of the given element. In this case, it returns “1”.

此属性返回给定元素的类型 。 在这种情况下,它返回“ 1 ”。

var container = document.querySelector('.container')
var getValue = container.nodeType;

But, what does “1” mean anyway? It is basically the nodeType of the given element. In this case, it is an _ELEMENT_NODE_ and returns null. If this were an attribute, it would be returned as “2” to us and the attribute value.

但是,“ 1 ”到底是什么意思? 它基本上是给定元素的nodeType 。 在这种情况下,它是_ELEMENT_NODE_并返回null。 如果这是一个属性,它将以“ 2 ”的形式返回给我们和属性值。

You can read more about nodeTypes here.

您可以在此处阅读有关nodeTypes的更多信息。

元素 (Elements)

These properties, instead of those above, return to us only elements. They are more often used and recommended because they can cause less confusion and are easier to understand.

这些属性(而不是上面的属性)仅返回给我们elements 。 它们更经常使用和推荐,因为它们可以减少混乱并且更易于理解。

.parentNode (.parentNode)

This property returns the parent of the node given.

此属性返回给定节点的父级。

var container = document.querySelector('.container')
var getParent = container.parentNode;

.firstElementChild (.firstElementChild)

Returns the first child element of the given element.

返回给定元素的第一个子元素。

var container = document.querySelector('.container')
var getValue = container.firstElementChild;

.lastElementChild (.lastElementChild)

Returns the last child element of the given element.

返回给定元素的最后一个子元素。

var container = document.querySelector('.container')
var getValue = container.lastElementChild;

These are some of the many properties that the DOM has. It’s very important for you to know the basics about the DOM, how it works, and its methods and properties, because some day you may need it.

这些是DOM具有的许多属性中的一些。 了解DOM的基本知识,它的工作方式以及它的方法和属性对您来说非常重要,因为有一天您可能会需要它。

结论 (Conclusion)

The DOM provides us with several important API's for creating fantastic and innovative applications. If you understand the basics of it you can create incredible things. If you want to read more about the DOM, you can click here and read all the MDN docs.

DOM为我们提供了几个重要的API,可用于创建出色的创新应用程序。 如果您了解它的基础知识,则可以创建令人难以置信的东西。 如果您想了解有关DOM的更多信息,可以单击此处并阅读所有MDN文档。

? Follow me on Twitter! Follow me on GitHub!

在Twitter上关注我! 在GitHub上关注我!

I’m looking for a remote opportunity, so if have any I’d love to hear about it, so please contact me!

我正在寻找机会,所以如果有任何我想听到的机会,请与我联系!

翻译自: https://www.freecodecamp.org/news/whats-the-document-object-model-and-why-you-should-know-how-to-use-it-1a2d0bc5429d/

文档对象模型dom

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/393171.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

安装Docker step by step

1. 系统要求 centos7以上 使用cat /etc/redhat-release查看系统版本&#xff0c;我的Centos 7.6 centos-extra 仓库 enable&#xff0c;默认是打开的 2.安装docker docer安装分为联网安装和离线安装两种安装 方式&#xff0c; 第一种 在有外网环境下安装docker,一般使用yum安…

linux用户空间和内核exit的语义--linux没有线程

如果你在程序中调用了exit&#xff0c;那么很显然你的程序会退出&#xff0c;可是至于为何会退出那就是库的事情了&#xff0c;我为什么说只是库的事情而不关linux内核的事情呢&#xff1f;那是因为linux内核根本不管用户空间的行为策略。库的策略是什么&#xff1f;很简单的退…

leetcode1328. 破坏回文串

给你一个回文字符串 palindrome &#xff0c;请你将其中 一个 字符用任意小写英文字母替换&#xff0c;使得结果字符串的字典序最小&#xff0c;且 不是 回文串。 请你返回结果字符串。如果无法做到&#xff0c;则返回一个空串。 示例 1&#xff1a; 输入&#xff1a;palindro…

php补充 扩展,PHP安装扩展补充说明

上一篇文章中用到了&#xff0c;php的sodium扩展&#xff0c;那么如何安装PHP扩展呢&#xff1f;基于我之前踩过的一些坑&#xff0c;大致整理了几种安装php扩展的方法。已安装sodium为例1、先做点准备工作&#xff0c;安装sodium依赖rpm -ivh http://mirrors.whsir.com/centos…

Java调用存储过程出现Bug,sql语法错误

因为SQL Server运行没有正常,检查了传入参数的值,发现问题,然后传入默认参数,解决了问题.转载于:https://www.cnblogs.com/JimmySeraph/p/11043490.html

leetcode1438. 绝对差不超过限制的最长连续子数组

给你一个整数数组 nums &#xff0c;和一个表示限制的整数 limit&#xff0c;请你返回最长连续子数组的长度&#xff0c;该子数组中的任意两个元素之间的绝对差必须小于或者等于 limit 。 如果不存在满足条件的子数组&#xff0c;则返回 0 。 示例 1&#xff1a; 输入&#…

gitlab 2.7版本升级到2.8

第一步 关闭服务 /etc/init.d/gitlab stop第二部 更新代码cd /home/gitlab/gitlab# Get latest codesudo -u gitlab git pull origin stable# Install libssudo -u gitlab bundle install --without development test# update dbsudo -u gitlab bundle exec rake db:migrate RA…

arkit技术介绍_面向移动AR的触觉技术:如何以“触摸”感增强ARKit应用

arkit技术介绍by Neil Mathew通过尼尔马修(Neil Mathew) 面向移动AR的触觉技术&#xff1a;如何以“触摸”感增强ARKit应用 (Haptics for mobile AR: how to enhance ARKit apps with a sense of “touch”) I’m really excited about the future of haptics for AR and VR. …

Unity3D的坑系列:动态加载dll

Unity3D的坑系列&#xff1a;动态加载dll 我现在参与的项目是做MMO手游&#xff0c;目标平台是Android和iOS&#xff0c;iOS平台不能动态加载dll&#xff08;什么原因找乔布斯去&#xff09;&#xff0c;可以直接忽略&#xff0c;而在Android平台是可以动态加载dll的&#xff0…

微信小程序 php配置,微信小程序的配置

我们使用app.json文件来对微信小程序进行全局配置&#xff0c;决定页面文件的路径、窗口表现、设置网络超时时间、设置多 tab 等。以下是一个包含了所有配置选项的简单配置app.json{"pages": ["pages/index/index","pages/logs/index"],"wi…

leetcode332. 重新安排行程(dfs)

给定一个机票的字符串二维数组 [from, to]&#xff0c;子数组中的两个成员分别表示飞机出发和降落的机场地点&#xff0c;对该行程进行重新规划排序。所有这些机票都属于一个从 JFK&#xff08;肯尼迪国际机场&#xff09;出发的先生&#xff0c;所以该行程必须从 JFK 开始。 …

PWA - service worker - Workbox(未完)

Get Started&#xff08;开始&#xff09; 只有get请求才能cache缓存吗&#xff1f;Create and Register a Service Worker File&#xff08;创建和注册 Service Worker&#xff09; Before we can use Workbox, we need to create a service worker file and register it to o…

draft.js_如何使用快捷方式在Draft.js中创建有序列表和无序列表

draft.jsby Andrey Semin通过安德烈塞米(Andrey Semin) 如何使用快捷方式在Draft.js中创建有序列表和无序列表 (How to create ordered and unordered lists in Draft.js with a shortcut) We at Propeller have encountered many differences between Draft.js and popular t…

当javaScript从入门到提高前需要注意的细节:变量部分

到了HTML5的时代&#xff0c;对javaScript的要求不是降低了&#xff0c;而是更提高了。javaScript语言的入门非常简单&#xff0c;如果你有java、C#等C风格的结构化语言的基础&#xff0c;那javaScript你最多半天就可以写点什么了。但是javaScript是一种动态语言&#xff0c;这…

PAT乙级 1003. 我要通过!

题目&#xff1a; “答案正确”是自动判题系统给出的最令人欢喜的回复。本题属于PAT的“答案正确”大派送 —— 只要读入的字符串满足下列条件&#xff0c;系统就输出“答案正确”&#xff0c;否则输出“答案错误”。 得到“答案正确”的条件是&#xff1a; 1. 字符串中必须仅有…

电台复活节_如何通过在控制台中隐藏复活节彩蛋使您的应用程序用户惊讶

电台复活节by Ethan Ryan由伊桑瑞安(Ethan Ryan) 如何通过在控制台中隐藏复活节彩蛋使您的应用程序用户惊讶 (How to surprise your app’s users by hiding Easter eggs in the console) I love console.logging(“stuff”).我喜欢console.logging(“ stuff”)。 I do it th…

leetcode1267. 统计参与通信的服务器(dfs)

这里有一幅服务器分布图&#xff0c;服务器的位置标识在 m * n 的整数矩阵网格 grid 中&#xff0c;1 表示单元格上有服务器&#xff0c;0 表示没有。 如果两台服务器位于同一行或者同一列&#xff0c;我们就认为它们之间可以进行通信。 请你统计并返回能够与至少一台其他服务…

System类入门学习

第三阶段 JAVA常见对象的学习 System类 System类包含一些有用的字段和方法&#xff0c;他不能被实例化 //用于垃圾回收 public static void gc()//终止正在运行的java虚拟机。参数用作状态码&#xff0c;根据惯例&#xff0c;非0表示异常终止 public static void exit(int stat…

gulpfile php,Laravel利用gulp如何构建前端资源详解

什么是gulp&#xff1f;gulp是新一代的前端项目构建工具&#xff0c;你可以使用gulp及其插件对你的项目代码(less,sass)进行编译&#xff0c;还可以压缩你的js和css代码&#xff0c;甚至压缩你的图片&#xff0c;gulp仅有少量的API&#xff0c;所以非常容易学习。 gulp 使用 st…

ios jenkins_如何使用Jenkins和Fastlane制作iOS点播构建系统

ios jenkinsby Agam Mahajan通过Agam Mahajan 如何使用Jenkins和Fastlane制作iOS点播构建系统 (How to make an iOS on-demand build system with Jenkins and Fastlane) This article is about creating iOS builds through Jenkins BOT, remotely, without the need of a de…