[TOC] # HTMLDOM基础知识 > 通过 HTML DOM, JavaScript 能够访问 HTML 文档中的每个元素。 DOM 是 Document Object Model(文档对象模型)的缩写。 学习`HTML DOM`作为基础,以后学习和理解`JavaScript`会非常容易。 DOM 定义了访问 HTML 和 XML 文档的标准: “W3C 文档对象模型 (DOM) 是中立于平台和语言的接口,它允许程序和脚本动态地访问和更新文档的内容、结构和样式。” W3C DOM 标准被分为 3 个不同的部分: - 核心 DOM - 针对任何结构化文档的标准模型 - XML DOM - 针对 XML 文档的标准模型 - HTML DOM - 针对 HTML 文档的标准模型 `HTML DOM` 定义了所有 `HTML` `元素`的`对象`和`属性`,以及访问它们的`方法`。 `HTML DOM` 是关于如何获取、修改、添加或删除 HTML 元素的标准。 ## `节点`与`节点树`概念 在 HTML DOM 中,所有事物都是`节点`。DOM 是被视为节点树的 HTML。 ![](https://box.kancloud.cn/2015-12-13_566d156ac641e.gif) 节点与节点之间的关系可以是: `父子关系(上下层)`、`兄弟关系(同层)`。 最顶层的节点叫做`根节点(root)`,他没有父节点和兄弟节点。 节点和节点树说的是对`HTML文档`的数据结构的抽象`存储结构`。 而具体的`对象` 在`节点`存储结构基础上实现的操作方法封装。 ## 属性Attributes对象 在`HTML DOM`中, 属性对象是属于一个`HTML元素`,包含了属性`name`、`value`属性和两个状态判断属性`isId`、`specified`。 属性的访问和处理函数有哪些呢?对于属性的操作是使用`NamedNodeMap`对象来完成的。下面了解下`NNM`吧。 ### NamedNodeMap(NNM)对象 NNM 对象表示一个元素属性节点的无序集合。在NNM中的节点可以通过`name`和`index(数字序号)`访问。 NNM对象的属性和方法如下: |Property / Method |Description | | :----| :----------| |attr.isId |判断属性是否是Id,True表示是,False表示不是,目前浏览器都删除对此属性的支持| |`attr.name` | 查看属性名称 | |attr.value | 设置或者查看属性值 | |attr.specified |查明是否已指定属性,True表示已指定或已创建但尚未附加到元素,False表示未指定 | ||| |nodemap.getNamedItem() |获取指定的属性节点| |nodemap.item() |返回NamedNodeMap上指定序号的属性节点| |nodemap.length |返回NamedNodeMap上属性的节点数量| |nodemap.removeNamedItem() |删除Removes a specified attribute node | |nodemap.setNamedItem() |Sets the specified attribute node (by name) | 示例: ```HTML <html> <body> <p id="intro" class="test" >Hello World!</p> <script> //var txt=document.getElementById("intro").innerHTML; var p=document.getElementById("intro"); var txt=p.attributes.getNamedItem('id').value document.write(txt); //获取<p>元素的第一个属性的名称: var x = document.getElementById("intro").attributes.item(0).nodeName; document.write('<br>' + x) </script> </body> </html> ``` 页面执行结果: ``` Hello World! intro id ``` ## HTMLDOM的Document对象 > 当HTML文档被加载到Web浏览器时 就在浏览器中变成了一个`document`对象, `document`对象就是这个`HTML`文档节点树的根节点。 操作`document`对象就是在操作这个节点树。 ### document对象的属性和方法 |Property / Method |Description | | :----| :--------------| |activeElement |Returns the currently focused element in the document | |addEventListener() |Attaches an event handler to the document | |adoptNode() |Adopts a node from another document | |anchors |Returns a collection of all \<a> elements in the document that have a name attribute | |applets |Returns a collection of all \<applet> elements in the document | |baseURI |Returns the absolute base URI of a document | |body |Sets or returns the document's body (the \<body> element) | |close() |Closes the output stream previously opened with document.open() | |cookie |Returns all name/value pairs of cookies in the document | |charset |Deprecated. Use characterSet instead. Returns the character encoding for the document | |characterSet |Returns the character encoding for the document | |createAttribute() |Creates an attribute node | |createComment() |Creates a Comment node with the specified text | |createDocumentFragment() |Creates an empty DocumentFragment node | |createElement() |Creates an Element node | |createEvent() |Creates a new event | |createTextNode() |Creates a Text node | |defaultView |Returns the window object associated with a document, or null if none is available. | |designMode |Controls whether the entire document should be editable or not. | |doctype |Returns the Document Type Declaration associated with the document | |documentElement |Returns the Document Element of the document (the \<html> element) | |documentMode |Returns the mode used by the browser to render the document | |documentURI |Sets or returns the location of the document | |domain |Returns the domain name of the server that loaded the document | |domConfig |Obsolete. Returns the DOM configuration of the document | |embeds |Returns a collection of all \<embed> elements the document | |execCommand() |Invokes the specified clipboard operation on the element currently having focus. | |forms |Returns a collection of all \<form> elements in the document | |fullscreenElement |Returns the current element that is displayed in fullscreen mode | |fullscreenEnabled() |Returns a Boolean value indicating whether the document can be viewed in fullscreen mode | |getElementById() |Returns the element that has the ID attribute with the specified value | |getElementsByClassName() |Returns a HTMLCollection containing all elements with the specified class name | |getElementsByName() |Returns a HTMLCollection containing all elements with a specified name | |getElementsByTagName() |Returns a HTMLCollection containing all elements with the specified tag name | |hasFocus() |Returns a Boolean value indicating whether the document has focus | |head |Returns the \<head> element of the document | |images |Returns a collection of all \<img> elements in the document | |implementation |Returns the DOMImplementation object that handles this document | |importNode() |Imports a node from another document | |inputEncoding |Returns the encoding, character set, used for the document | |lastModified |Returns the date and time the document was last modified | |links |Returns a collection of all \<a> and \<area> elements in the document that have a href attribute | |normalize() |Removes empty Text nodes, and joins adjacent nodes | |normalizeDocument() |Removes empty Text nodes, and joins adjacent nodes | |open() |Opens an HTML output stream to collect output from document.write() | |querySelector() |Returns the first element that matches a specified CSS selector(s) in the document | |querySelectorAll() |Returns a static NodeList containing all elements that matches a specified CSS selector(s) in the document | |readyState |Returns the (loading) status of the document | |referrer |Returns the URL of the document that loaded the current document | |removeEventListener() |Removes an event handler from the document (that has been attached with the addEventListener() method) | |renameNode() |Renames the specified node | |scripts |Returns a collection of \<script> elements in the document | |strictErrorChecking |Sets or returns whether error-checking is enforced or not | |title |Sets or returns the title of the document | |URL |Returns the full URL of the HTML document | |write() |Writes HTML expressions or JavaScript code to a document | |writeln() |Same as write(), but adds a newline character after each statement | ## `Element`元素对象 > `Element`对象表示的是`HTML`页面的元素,例如 `p`,`input`,`DIV`等等其他任何HTML元素。 ### `Element`元素对象的属性和方法 > 下面属性和方法适用于所有的`HTML`元素 |Property / Method |Description | | :----| :--------------| |accessKey |Sets or returns the accesskey attribute of an element | |addEventListener() |Attaches an event handler to the specified element | |appendChild() |Adds a new child node, to an element, as the last child node | |attributes |Returns a NamedNodeMap of an element's attributes | |blur() |Removes focus from an element | |childElementCount |Returns the number of child elements an element has | |childNodes |Returns a collection of an element's child nodes (including text and comment nodes) | |children |Returns a collection of an element's child element (excluding text and comment nodes) | |classList |Returns the class name(s) of an element | |className |Sets or returns the value of the class attribute of an element | |click() |Simulates a mouse-click on an element | |clientHeight |Returns the height of an element, including padding | |clientLeft |Returns the width of the left border of an element | |clientTop |Returns the width of the top border of an element | |clientWidth |Returns the width of an element, including padding | |cloneNode() |Clones an element | |compareDocumentPosition() |Compares the document position of two elements | |contains() |Returns true if a node is a descendant of a node, otherwise false | |contentEditable |Sets or returns whether the content of an element is editable or not | |dir |Sets or returns the value of the dir attribute of an element | |exitFullscreen() |Cancels an element in fullscreen mode | |firstChild |Returns the first child node of an element | |firstElementChild |Returns the first child element of an element | |focus() |Gives focus to an element | |getAttribute() |Returns the specified attribute value of an element node | |getAttributeNode() |Returns the specified attribute node | |getBoundingClientRect() |Returns the size of an element and its position relative to the viewport | |getElementsByClassName() |Returns a collection of all child elements with the specified class name | |getElementsByTagName() |Returns a collection of all child elements with the specified tag name | |hasAttribute() |Returns true if an element has the specified attribute, otherwise false | |hasAttributes() |Returns true if an element has any attributes, otherwise false | |hasChildNodes() |Returns true if an element has any child nodes, otherwise false | |id |Sets or returns the value of the id attribute of an element | |innerHTML |Sets or returns the content of an element | |innerText |Sets or returns the text content of a node and its descendants | |insertAdjacentElement() |Inserts a HTML element at the specified position relative to the current element | |insertAdjacentHTML() |Inserts a HTML formatted text at the specified position relative to the current element | |insertAdjacentText() |Inserts text into the specified position relative to the current element | |insertBefore() |Inserts a new child node before a specified, existing, child node | |isContentEditable |Returns true if the content of an element is editable, otherwise false | |isDefaultNamespace() |Returns true if a specified namespaceURI is the default, otherwise false | |isEqualNode() |Checks if two elements are equal | |isSameNode() |Checks if two elements are the same node | |isSupported() |Returns true if a specified feature is supported on the element | |lang |Sets or returns the value of the lang attribute of an element | |lastChild |Returns the last child node of an element | |lastElementChild |Returns the last child element of an element | |namespaceURI |Returns the namespace URI of an element | |nextSibling |Returns the next node at the same node tree level | |nextElementSibling |Returns the next element at the same node tree level | |nodeName |Returns the name of a node | |nodeType |Returns the node type of a node | |nodeValue |Sets or returns the value of a node | |normalize() |Joins adjacent text nodes and removes empty text nodes in an element | |offsetHeight |Returns the height of an element, including padding, border and scrollbar | |offsetWidth |Returns the width of an element, including padding, border and scrollbar | |offsetLeft |Returns the horizontal offset position of an element | |offsetParent |Returns the offset container of an element | |offsetTop |Returns the vertical offset position of an element | |outerHTML |Sets or returns the content of an element (including the start tag and the end tag) | |outerText |Sets or returns the outer text content of a node and its descendants | |ownerDocument |Returns the root element (document object) for an element | |parentNode |Returns the parent node of an element | |parentElement |Returns the parent element node of an element | |previousSibling |Returns the previous node at the same node tree level | |previousElementSibling |Returns the previous element at the same node tree level | |querySelector() |Returns the first child element that matches a specified CSS selector(s) of an element | |querySelectorAll() |Returns all child elements that matches a specified CSS selector(s) of an element | |remove() |Removes the element from the DOM | |removeAttribute() |Removes a specified attribute from an element | |removeAttributeNode() |Removes a specified attribute node, and returns the removed node | |removeChild() |Removes a child node from an element | |removeEventListener() |Removes an event handler that has been attached with the addEventListener() method | |replaceChild() |Replaces a child node in an element | |requestFullscreen() |Shows an element in fullscreen mode | |scrollHeight |Returns the entire height of an element, including padding | |scrollIntoView() |Scrolls the specified element into the visible area of the browser window | |scrollLeft |Sets or returns the number of pixels an element's content is scrolled horizontally | |scrollTop |Sets or returns the number of pixels an element's content is scrolled vertically | |scrollWidth |Returns the entire width of an element, including padding | |setAttribute() |Sets or changes the specified attribute, to the specified value | |setAttributeNode() |Sets or changes the specified attribute node | |style |Sets or returns the value of the style attribute of an element | |tabIndex |Sets or returns the value of the tabindex attribute of an element | |tagName |Returns the tag name of an element | |textContent |Sets or returns the textual content of a node and its descendants | |title |Sets or returns the value of the title attribute of an element | |toString() |Converts an element to a string | ## HTMLDOM的Events事件对象 `HTML DOM`事件允许 `JavaScript` 在HTML文档中的元素上注册不同的事件处理程序。 事件通常与功能结合使用,并且在事件发生之前(例如,用户单击按钮时)不会执行该功能。 |Event |Description |Belongs To | | :----| :---------------| :----| |abort |The event occurs when the loading of a media is aborted |UiEvent, Event | |afterprint |The event occurs when a page has started printing, or if the print dialogue box has been closed |Event | |animationend |The event occurs when a CSS animation has completed |AnimationEvent | |animationiteration |The event occurs when a CSS animation is repeated |AnimationEvent | |animationstart |The event occurs when a CSS animation has started |AnimationEvent | |beforeprint |The event occurs when a page is about to be printed |Event | |beforeunload |The event occurs before the document is about to be unloaded |UiEvent, Event | |blur |The event occurs when an element loses focus |FocusEvent | |canplay |The event occurs when the browser can start playing the media (when it has buffered enough to begin) |Event | |canplaythrough |The event occurs when the browser can play through the media without stopping for buffering |Event | |change |The event occurs when the content of a form element, the selection, or the checked state have changed (for \<input>, \<select>, and \<textarea>) |Event | |click |The event occurs when the user clicks on an element |MouseEvent | |contextmenu |The event occurs when the user right-clicks on an element to open a context menu |MouseEvent | |copy |The event occurs when the user copies the content of an element |ClipboardEvent | |cut |The event occurs when the user cuts the content of an element |ClipboardEvent | |dblclick |The event occurs when the user double-clicks on an element |MouseEvent | |drag |The event occurs when an element is being dragged |DragEvent | |dragend |The event occurs when the user has finished dragging an element |DragEvent | |dragenter |The event occurs when the dragged element enters the drop target |DragEvent | |dragleave |The event occurs when the dragged element leaves the drop target |DragEvent | |dragover |The event occurs when the dragged element is over the drop target |DragEvent | |dragstart |The event occurs when the user starts to drag an element |DragEvent | |drop |The event occurs when the dragged element is dropped on the drop target |DragEvent | |durationchange |The event occurs when the duration of the media is changed |Event | |ended |The event occurs when the media has reach the end (useful for messages like "thanks for listening") |Event | |error |The event occurs when an error occurs while loading an external file |ProgressEvent, UiEvent, Event | |focus |The event occurs when an element gets focus |FocusEvent | |focusin |The event occurs when an element is about to get focus |FocusEvent | |focusout |The event occurs when an element is about to lose focus |FocusEvent | |fullscreenchange |The event occurs when an element is displayed in fullscreen mode |Event | |fullscreenerror |The event occurs when an element can not be displayed in fullscreen mode |Event | |hashchange |The event occurs when there has been changes to the anchor part of a URL |HashChangeEvent | |input |The event occurs when an element gets user input |InputEvent, Event | |invalid |The event occurs when an element is invalid |Event | |keydown |The event occurs when the user is pressing a key |KeyboardEvent | |keypress |The event occurs when the user presses a key |KeyboardEvent | |keyup |The event occurs when the user releases a key |KeyboardEvent | |load |The event occurs when an object has loaded |UiEvent, Event | |loadeddata |The event occurs when media data is loaded |Event | |loadedmetadata |The event occurs when meta data (like dimensions and duration) are loaded |Event | |loadstart |The event occurs when the browser starts looking for the specified media |ProgressEvent | |message |The event occurs when a message is received through the event source |Event | |mousedown |The event occurs when the user presses a mouse button over an element |MouseEvent | |mouseenter |The event occurs when the pointer is moved onto an element |MouseEvent | |mouseleave |The event occurs when the pointer is moved out of an element |MouseEvent | |mousemove |The event occurs when the pointer is moving while it is over an element |MouseEvent | |mouseover |The event occurs when the pointer is moved onto an element, or onto one of its children |MouseEvent | |mouseout |The event occurs when a user moves the mouse pointer out of an element, or out of one of its children |MouseEvent | |mouseup |The event occurs when a user releases a mouse button over an element |MouseEvent | |mousewheel |Deprecated. Use the wheel event instead |WheelEvent | |offline |The event occurs when the browser starts to work offline |Event | |online |The event occurs when the browser starts to work online |Event | |open |The event occurs when a connection with the event source is opened |Event | |pagehide |The event occurs when the user navigates away from a webpage |PageTransitionEvent | |pageshow |The event occurs when the user navigates to a webpage |PageTransitionEvent | |paste |The event occurs when the user pastes some content in an element |ClipboardEvent | |pause |The event occurs when the media is paused either by the user or programmatically |Event | |play |The event occurs when the media has been started or is no longer paused |Event | |playing |The event occurs when the media is playing after having been paused or stopped for buffering |Event | |popstate |The event occurs when the window's history changes |PopStateEvent | |progress |The event occurs when the browser is in the process of getting the media data (downloading the media) |Event | |ratechange |The event occurs when the playing speed of the media is changed |Event | |resize |The event occurs when the document view is resized |UiEvent, Event | |reset |The event occurs when a form is reset |Event | |scroll |The event occurs when an element's scrollbar is being scrolled |UiEvent, Event | |search |The event occurs when the user writes something in a search field (for \<input="search">) |Event | |seeked |The event occurs when the user is finished moving/skipping to a new position in the media |Event | |seeking |The event occurs when the user starts moving/skipping to a new position in the media |Event | |select |The event occurs after the user selects some text (for \<input> and \<textarea>) |UiEvent, Event | |show |The event occurs when a \<menu> element is shown as a context menu |Event | |stalled |The event occurs when the browser is trying to get media data, but data is not available |Event | |storage |The event occurs when a Web Storage area is updated |StorageEvent | |submit |The event occurs when a form is submitted |Event | |suspend |The event occurs when the browser is intentionally not getting media data |Event | |timeupdate |The event occurs when the playing position has changed (like when the user fast forwards to a different point in the media) |Event | |toggle |The event occurs when the user opens or closes the \<details> element |Event | |touchcancel |The event occurs when the touch is interrupted |TouchEvent | |touchend |The event occurs when a finger is removed from a touch screen |TouchEvent | |touchmove |The event occurs when a finger is dragged across the screen |TouchEvent | |touchstart |The event occurs when a finger is placed on a touch screen |TouchEvent | |transitionend |The event occurs when a CSS transition has completed |TransitionEvent | |unload |The event occurs once a page has unloaded (for \<body>) |UiEvent, Event | |volumechange |The event occurs when the volume of the media has changed (includes setting the volume to "mute") |Event | |waiting |The event occurs when the media has paused but is expected to resume (like when the media pauses to buffer more data) |Event | |wheel |The event occurs when the mouse wheel rolls up or down over an element |WheelEvent | ### HTMLDOM的Event事件对象的属性和方法 |Property/Method |Description |Belongs To | | :----| :---------------| :----| |altKey |Returns whether the "ALT" key was pressed when the mouse event was triggered |MouseEvent | |altKey |Returns whether the "ALT" key was pressed when the key event was triggered |KeyboardEvent, TouchEvent | |animationName |Returns the name of the animation |AnimationEvent | |bubbles |Returns whether or not a specific event is a bubbling event |Event | |button |Returns which mouse button was pressed when the mouse event was triggered |MouseEvent | |buttons |Returns which mouse buttons were pressed when the mouse event was triggered |MouseEvent | |cancelable |Returns whether or not an event can have its default action prevented |Event | |charCode |Returns the Unicode character code of the key that triggered the onkeypress event |KeyboardEvent | |changeTouches |Returns a list of all the touch objects whose state changed between the previous touch and this touch |TouchEvent | |clientX |Returns the horizontal coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered |MouseEvent, TouchEvent | |clientY |Returns the vertical coordinate of the mouse pointer, relative to the current window, when the mouse event was triggered |MouseEvent, TouchEvent | |clipboardData |Returns an object containing the data affected by the clipboard operation |ClipboardData | |code |Returns the code of the key that triggered the event |KeyboardEvent | |composed |Returns whether the event is composed or not |Event | |createEvent() |Creates a new event |Event | |ctrlKey |Returns whether the "CTRL" key was pressed when the mouse event was triggered |MouseEvent | |ctrlKey |Returns whether the "CTRL" key was pressed when the key event was triggered |KeyboardEvent, TouchEvent | |currentTarget |Returns the element whose event listeners triggered the event |Event | |data |Returns the inserted characters |InputEvent | |dataTransfer |Returns an object containing the data being dragged/dropped, or inserted/deleted |DragEvent, InputEvent | |defaultPrevented |Returns whether or not the preventDefault() method was called for the event |Event | |deltaX |Returns the horizontal scroll amount of a mouse wheel (x-axis) |WheelEvent | |deltaY |Returns the vertical scroll amount of a mouse wheel (y-axis) |WheelEvent | |deltaZ |Returns the scroll amount of a mouse wheel for the z-axis |WheelEvent | |deltaMode |Returns a number that represents the unit of measurements for delta values (pixels, lines or pages) |WheelEvent | |detail |Returns a number that indicates how many times the mouse was clicked |UiEvent | |elapsedTime |Returns the number of seconds an animation has been running |AnimationEvent | |elapsedTime |Returns the number of seconds a transition has been running | | |eventPhase |Returns which phase of the event flow is currently being evaluated |Event | |getTargetRanges() |Returns an array containing target ranges that will be affected by the insertion/deletion |InputEvent | |getModifierState() |Returns an array containing target ranges that will be affected by the insertion/deletion |MouseEvent | |inputType |Returns the type of the change (i.e "inserting" or "deleting") |InputEvent | |isComposing |Returns whether the state of the event is composing or not |InputEvent, KeyboardEvent | |isTrusted |Returns whether or not an event is trusted |Event | |key |Returns the key value of the key represented by the event |KeyboardEvent | |key |Returns the key of the changed storage item |StorageEvent | |keyCode |Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event |KeyboardEvent | |location |Returns the location of a key on the keyboard or device |KeyboardEvent | |lengthComputable |Returns whether the length of the progress can be computable or not |ProgressEvent | |loaded |Returns how much work has been loaded |ProgressEvent | |metaKey |Returns whether the "META" key was pressed when an event was triggered |MouseEvent | |metaKey |Returns whether the "meta" key was pressed when the key event was triggered |KeyboardEvent, TouchEvent | |MovementX |Returns the horizontal coordinate of the mouse pointer relative to the position of the last mousemove event |MouseEvent | |MovementY |Returns the vertical coordinate of the mouse pointer relative to the position of the last mousemove event |MouseEvent | |newValue |Returns the new value of the changed storage item |StorageEvent | |newURL |Returns the URL of the document, after the hash has been changed |HasChangeEvent | |offsetX |Returns the horizontal coordinate of the mouse pointer relative to the position of the edge of the target element |MouseEvent | |offsetY |Returns the vertical coordinate of the mouse pointer relative to the position of the edge of the target element |MouseEvent | |oldValue |Returns the old value of the changed storage item |StorageEvent | |oldURL |Returns the URL of the document, before the hash was changed |HasChangeEvent | |onemptied |The event occurs when something bad happens and the media file is suddenly unavailable (like unexpectedly disconnects) | | |pageX |Returns the horizontal coordinate of the mouse pointer, relative to the document, when the mouse event was triggered |MouseEvent | |pageY |Returns the vertical coordinate of the mouse pointer, relative to the document, when the mouse event was triggered |MouseEvent | |persisted |Returns whether the webpage was cached by the browser |PageTransitionEvent | |preventDefault() |Cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur |Event | |propertyName |Returns the name of the CSS property associated with the animation or transition |AnimationEvent, TransitionEvent | |pseudoElement |Returns the name of the pseudo-element of the animation or transition |AnimationEvent, TransitionEvent | |region | |MouseEvent | |relatedTarget |Returns the element related to the element that triggered the mouse event |MouseEvent | |relatedTarget |Returns the element related to the element that triggered the event |FocusEvent | |repeat |Returns whether a key is being hold down repeatedly, or not |KeyboardEvent | |screenX |Returns the horizontal coordinate of the mouse pointer, relative to the screen, when an event was triggered |MouseEvent | |screenY |Returns the vertical coordinate of the mouse pointer, relative to the screen, when an event was triggered |MouseEvent | |shiftKey |Returns whether the "SHIFT" key was pressed when an event was triggered |MouseEvent | |shiftKey |Returns whether the "SHIFT" key was pressed when the key event was triggered |KeyboardEvent, TouchEvent | |state |Returns an object containing a copy of the history entries |PopStateEvent | |stopImmediatePropagation() |Prevents other listeners of the same event from being called |Event | |stopPropagation() |Prevents further propagation of an event during event flow |Event | |storageArea |Returns an object representing the affected storage object |StorageEvent | |target |Returns the element that triggered the event |Event | |targetTouches |Returns a list of all the touch objects that are in contact with the surface and where the touchstart event occured on the same target element as the current target element |TouchEvent | |timeStamp |Returns the time (in milliseconds relative to the epoch) at which the event was created |Event | |total |Returns the total amount of work that will be loaded |ProgressEvent | |touches |Returns a list of all the touch objects that are currently in contact with the surface |TouchEvent | |transitionend |The event occurs when a CSS transition has completed |TransitionEvent | |type |Returns the name of the event |Event | |url |Returns the URL of the changed item's document |StorageEvent | |which |Returns which mouse button was pressed when the mouse event was triggered |MouseEvent | |which |Returns the Unicode character code of the key that triggered the onkeypress event, or the Unicode key code of the key that triggered the onkeydown or onkeyup event |KeyboardEvent | |view |Returns a reference to the Window object where the event occurred |UiEvent | ### 关于事件对象 > 当HTML中发生事件时,该事件属于某个事件对象,例如,鼠标单击事件属于MouseEvent对象。 所有事件对象均基于`Event`事件对象,并继承其所有属性和方法。 #### 基于`Event`事件对象事件的常见事件对象 这些是最常见的事件对象: |Event Object |Description | | :----| :---------| |AnimationEvent |For CSS animations | |ClipboardEvent |For modification of the clipboard | |DragEvent |For drag and drop interaction | |FocusEvent |For focus-related events | |HashChangeEvent |For changes in the anchor part of the URL | |InputEvent |For user input | |KeyboardEvent |For keyboard interaction | |MouseEvent |For mouse interaction | |PageTransitionEvent |For navigating to, and away from, web pages | |PopStateEvent |For changes in the history entry | |ProgressEvent |For the progress of loading external resources | |StorageEvent |For changes in the window's storage area. | |TouchEvent |For touch interaction | |TransitionEvent |For CSS transitions | |UiEvent |For user interface interaction | |WheelEvent |For mousewheel interaction | ## `HTML DOM`Collection集合对象 `HTMLCollection`对象是HTML元素的类似数组的列表。 诸如 `getElementsByTagName()`之类的方法将返回`HTMLCollection`。 ### HTML集合的属性和方法 可以在HTMLCollection对象上使用以下属性和方法: |Property / Method |Description | | :----| :------------| |item() |Returns the element at the specified index in an HTMLCollection | |length |Returns the number of elements in an HTMLCollection | |namedItem() |Returns the element with the specified ID, or name, in an HTMLCollection | **示例: 循环遍历HTMLCollection中的每个元素:** ```JavaScript x = document.getElementsByTagName("P"); l = x.length; for (i = 0; i < l; i++) { document.write(x[i].tagName + "<br>"); } ``` ## `location`位置对象 位置对象包含有关当前`URL`的信息。 location对象是window对象的一部分,可以通过window.location属性进行访问。 注意:没有适用于位置对象的公共标准,但是所有主流浏览器都支持它。 ### 位置对象属性 |Property |Description | | :----| :-----------| |hash |Sets or returns the anchor part (#) of a URL | |host |Sets or returns the hostname and port number of a URL | |hostname |Sets or returns the hostname of a URL | |href |Sets or returns the entire URL | |origin |Returns the protocol, hostname and port number of a URL | |pathname |Sets or returns the path name of a URL | |port |Sets or returns the port number of a URL | |protocol |Sets or returns the protocol of a URL | |search |Sets or returns the querystring part of a URL | ### 定位对象方法 |Method |Description | | :----| :--------| |assign() |Loads a new document | |reload() |Reloads the current document | |replace() |Replaces the current document with a new one | ## 导航器对象 导航器对象包含有关浏览器的信息。 注意:没有适用于导航器对象的公共标准,但是所有主要的浏览器都支持它。 ### 导航器对象属性 |Property |Description | | :----| :--------------| |appCodeName |Returns the code name of the browser | |appName |Returns the name of the browser | |appVersion |Returns the version information of the browser | |cookieEnabled |Determines whether cookies are enabled in the browser | |geolocation |Returns a Geolocation object that can be used to locate the user's position | |language |Returns the language of the browser | |onLine |Determines whether the browser is online | |platform |Returns for which platform the browser is compiled | |product |Returns the engine name of the browser | |userAgent |Returns the user-agent header sent by the browser to the server | ### 导航器对象方法 |Method |Description | | :----| :-------------| |javaEnabled() | 指定浏览器是否启用了Java支持 | |taintEnabled() |`Removed in JavaScript version 1.2.` 指定浏览器是否启用了数据污染 | ## 屏幕对象 屏幕对象包含有关访客屏幕的信息。 注意:没有适用于屏幕对象的公共标准,但是所有主要的浏览器都支持它。 ### 屏幕对象属性 |Property |Description | | :----| :------------| |availHeight |Returns the height of the screen (excluding the Windows Taskbar) | |availWidth |Returns the width of the screen (excluding the Windows Taskbar) | |colorDepth |Returns the bit depth of the color palette for displaying images | |height |Returns the total height of the screen | |pixelDepth |Returns the color resolution (in bits per pixel) of the screen | |width |Returns the total width of the screen | ## HTMLDOM的Style样式对象 Style对象代表单个样式声明。 ### 样式对象属性 “ CSS”列指示该属性在哪个CSS版本中定义(CSS1,CSS2或CSS3)。 |Property |Description |CSS | | :------| :---------------| :---| |alignContent |Sets or returns the alignment between the lines inside a flexible container when the items do not use all available space |3 | |alignItems |Sets or returns the alignment for items inside a flexible container |3 | |alignSelf |Sets or returns the alignment for selected items inside a flexible container |3 | |animation |A shorthand property for all the animation properties below, except the animationPlayState property |3 | |animationDelay |Sets or returns when the animation will start |3 | |animationDirection |Sets or returns whether or not the animation should play in reverse on alternate cycles |3 | |animationDuration |Sets or returns how many seconds or milliseconds an animation takes to complete one cycle |3 | |animationFillMode |Sets or returns what values are applied by the animation outside the time it is executing |3 | |animationIterationCount |Sets or returns the number of times an animation should be played |3 | |animationName |Sets or returns a name for the @keyframes animation |3 | |animationTimingFunction |Sets or returns the speed curve of the animation |3 | |animationPlayState |Sets or returns whether the animation is running or paused |3 | |background |Sets or returns all the background properties in one declaration |1 | |backgroundAttachment |Sets or returns whether a background-image is fixed or scrolls with the page |1 | |backgroundColor |Sets or returns the background-color of an element |1 | |backgroundImage |Sets or returns the background-image for an element |1 | |backgroundPosition |Sets or returns the starting position of a background-image |1 | |backgroundRepeat |Sets or returns how to repeat (tile) a background-image |1 | |backgroundClip |Sets or returns the painting area of the background |3 | |backgroundOrigin |Sets or returns the positioning area of the background images |3 | |backgroundSize |Sets or returns the size of the background image |3 | |backfaceVisibility |Sets or returns whether or not an element should be visible when not facing the screen |3 | |border |Sets or returns borderWidth, borderStyle, and borderColor in one declaration |1 | |borderBottom |Sets or returns all the borderBottom properties in one declaration |1 | |borderBottomColor |Sets or returns the color of the bottom border |1 | |borderBottomLeftRadius |Sets or returns the shape of the border of the bottom-left corner |3 | |borderBottomRightRadius |Sets or returns the shape of the border of the bottom-right corner |3 | |borderBottomStyle |Sets or returns the style of the bottom border |1 | |borderBottomWidth |Sets or returns the width of the bottom border |1 | |borderCollapse |Sets or returns whether the table border should be collapsed into a single border, or not |2 | |borderColor |Sets or returns the color of an element's border (can have up to four values) |1 | |borderImage |A shorthand property for setting or returning all the borderImage properties |3 | |borderImageOutset |Sets or returns the amount by which the border image area extends beyond the border box |3 | |borderImageRepeat |Sets or returns whether the image-border should be repeated, rounded or stretched |3 | |borderImageSlice |Sets or returns the inward offsets of the image-border |3 | |borderImageSource |Sets or returns the image to be used as a border |3 | |borderImageWidth |Sets or returns the widths of the image-border |3 | |borderLeft |Sets or returns all the borderLeft properties in one declaration |1 | |borderLeftColor |Sets or returns the color of the left border |1 | |borderLeftStyle |Sets or returns the style of the left border |1 | |borderLeftWidth |Sets or returns the width of the left border |1 | |borderRadius |A shorthand property for setting or returning all the four borderRadius properties |3 | |borderRight |Sets or returns all the borderRight properties in one declaration |1 | |borderRightColor |Sets or returns the color of the right border |1 | |borderRightStyle |Sets or returns the style of the right border |1 | |borderRightWidth |Sets or returns the width of the right border |1 | |borderSpacing |Sets or returns the space between cells in a table |2 | |borderStyle |Sets or returns the style of an element's border (can have up to four values) |1 | |borderTop |Sets or returns all the borderTop properties in one declaration |1 | |borderTopColor |Sets or returns the color of the top border |1 | |borderTopLeftRadius |Sets or returns the shape of the border of the top-left corner |3 | |borderTopRightRadius |Sets or returns the shape of the border of the top-right corner |3 | |borderTopStyle |Sets or returns the style of the top border |1 | |borderTopWidth |Sets or returns the width of the top border |1 | |borderWidth |Sets or returns the width of an element's border (can have up to four values) |1 | |bottom |Sets or returns the bottom position of a positioned element |2 | |boxDecorationBreak |Sets or returns the behaviour of the background and border of an element at page-break, or, for in-line elements, at line-break. |3 | |boxShadow |Attaches one or more drop-shadows to the box |3 | |boxSizing |Allows you to define certain elements to fit an area in a certain way |3 | |captionSide |Sets or returns the position of the table caption |2 | |clear |Sets or returns the position of the element relative to floating objects |1 | |clip |Sets or returns which part of a positioned element is visible |2 | |color |Sets or returns the color of the text |1 | |columnCount |Sets or returns the number of columns an element should be divided into |3 | |columnFill |Sets or returns how to fill columns |3 | |columnGap |Sets or returns the gap between the columns |3 | |columnRule |A shorthand property for setting or returning all the columnRule properties |3 | |columnRuleColor |Sets or returns the color of the rule between columns |3 | |columnRuleStyle |Sets or returns the style of the rule between columns |3 | |columnRuleWidth |Sets or returns the width of the rule between columns |3 | |columns |A shorthand property for setting or returning columnWidth and columnCount |3 | |columnSpan |Sets or returns how many columns an element should span across |3 | |columnWidth |Sets or returns the width of the columns |3 | |content |Used with the :before and :after pseudo-elements, to insert generated content |2 | |counterIncrement |Increments one or more counters |2 | |counterReset |Creates or resets one or more counters |2 | |cursor |Sets or returns the type of cursor to display for the mouse pointer |2 | |direction |Sets or returns the text direction |2 | |display |Sets or returns an element's display type |1 | |emptyCells |Sets or returns whether to show the border and background of empty cells, or not |2 | |filter |Sets or returns image filters (visual effects, like blur and saturation) |3 | |flex |Sets or returns the length of the item, relative to the rest |3 | |flexBasis |Sets or returns the initial length of a flexible item |3 | |flexDirection |Sets or returns the direction of the flexible items |3 | |flexFlow |A shorthand property for the flexDirection and the flexWrap properties |3 | |flexGrow |Sets or returns how much the item will grow relative to the rest |3 | |flexShrink |Sets or returns how the item will shrink relative to the rest |3 | |flexWrap |Sets or returns whether the flexible items should wrap or not |3 | |cssFloat |Sets or returns the horizontal alignment of an element |1 | |font |Sets or returns fontStyle, fontVariant, fontWeight, fontSize, lineHeight, and fontFamily in one declaration |1 | |fontFamily |Sets or returns the font family for text |1 | |fontSize |Sets or returns the font size of the text |1 | |fontStyle |Sets or returns whether the style of the font is normal, italic or oblique |1 | |fontVariant |Sets or returns whether the font should be displayed in small capital letters |1 | |fontWeight |Sets or returns the boldness of the font |1 | |fontSizeAdjust |Preserves the readability of text when font fallback occurs |3 | |fontStretch |Selects a normal, condensed, or expanded face from a font family |3 | |hangingPunctuation |Specifies whether a punctuation character may be placed outside the line box |3 | |height |Sets or returns the height of an element |1 | |hyphens |Sets how to split words to improve the layout of paragraphs |3 | |icon |Provides the author the ability to style an element with an iconic equivalent |3 | |imageOrientation |Specifies a rotation in the right or clockwise direction that a user agent applies to an image |3 | |isolation |Defines whether an element must create a new stacking content |3 | |justifyContent |Sets or returns the alignment between the items inside a flexible container when the items do not use all available space. |3 | |left |Sets or returns the left position of a positioned element |2 | |letterSpacing |Sets or returns the space between characters in a text |1 | |lineHeight |Sets or returns the distance between lines in a text |1 | |listStyle |Sets or returns listStyleImage, listStylePosition, and listStyleType in one declaration |1 | |listStyleImage |Sets or returns an image as the list-item marker |1 | |listStylePosition |Sets or returns the position of the list-item marker |1 | |listStyleType |Sets or returns the list-item marker type |1 | |margin |Sets or returns the margins of an element (can have up to four values) |1 | |marginBottom |Sets or returns the bottom margin of an element |1 | |marginLeft |Sets or returns the left margin of an element |1 | |marginRight |Sets or returns the right margin of an element |1 | |marginTop |Sets or returns the top margin of an element |1 | |maxHeight |Sets or returns the maximum height of an element |2 | |maxWidth |Sets or returns the maximum width of an element |2 | |minHeight |Sets or returns the minimum height of an element |2 | |minWidth |Sets or returns the minimum width of an element |2 | |navDown |Sets or returns where to navigate when using the arrow-down navigation key |3 | |navIndex |Sets or returns the tabbing order for an element |3 | |navLeft |Sets or returns where to navigate when using the arrow-left navigation key |3 | |navRight |Sets or returns where to navigate when using the arrow-right navigation key |3 | |navUp |Sets or returns where to navigate when using the arrow-up navigation key |3 | |objectFit |Specifies how the contents of a replaced element should be fitted to the box established by its used height and width |3 | |objectPosition |Specifies the alignment of the replaced element inside its box |3 | |opacity |Sets or returns the opacity level for an element |3 | |order |Sets or returns the order of the flexible item, relative to the rest |3 | |orphans |Sets or returns the minimum number of lines for an element that must be left at the bottom of a page when a page break occurs inside an element |2 | |outline |Sets or returns all the outline properties in one declaration |2 | |outlineColor |Sets or returns the color of the outline around a element |2 | |outlineOffset |Offsets an outline, and draws it beyond the border edge |3 | |outlineStyle |Sets or returns the style of the outline around an element |2 | |outlineWidth |Sets or returns the width of the outline around an element |2 | |overflow |Sets or returns what to do with content that renders outside the element box |2 | |overflowX |Specifies what to do with the left/right edges of the content, if it overflows the element's content area |3 | |overflowY |Specifies what to do with the top/bottom edges of the content, if it overflows the element's content area |3 | |padding |Sets or returns the padding of an element (can have up to four values) |1 | |paddingBottom |Sets or returns the bottom padding of an element |1 | |paddingLeft |Sets or returns the left padding of an element |1 | |paddingRight |Sets or returns the right padding of an element |1 | |paddingTop |Sets or returns the top padding of an element |1 | |pageBreakAfter |Sets or returns the page-break behavior after an element |2 | |pageBreakBefore |Sets or returns the page-break behavior before an element |2 | |pageBreakInside |Sets or returns the page-break behavior inside an element |2 | |perspective |Sets or returns the perspective on how 3D elements are viewed |3 | |perspectiveOrigin |Sets or returns the bottom position of 3D elements |3 | |position |Sets or returns the type of positioning method used for an element (static, relative, absolute or fixed) |2 | |quotes |Sets or returns the type of quotation marks for embedded quotations |2 | |resize |Sets or returns whether or not an element is resizable by the user |3 | |right |Sets or returns the right position of a positioned element |2 | |tableLayout |Sets or returns the way to lay out table cells, rows, and columns |2 | |tabSize |Sets or returns the length of the tab-character |3 | |textAlign |Sets or returns the horizontal alignment of text |1 | |textAlignLast |Sets or returns how the last line of a block or a line right before a forced line break is aligned when text-align is "justify" |3 | |textDecoration |Sets or returns the decoration of a text |1 | |textDecorationColor |Sets or returns the color of the text-decoration |3 | |textDecorationLine |Sets or returns the type of line in a text-decoration |3 | |textDecorationStyle |Sets or returns the style of the line in a text decoration |3 | |textIndent |Sets or returns the indentation of the first line of text |1 | |textJustify |Sets or returns the justification method used when text-align is "justify" |3 | |textOverflow |Sets or returns what should happen when text overflows the containing element |3 | |textShadow |Sets or returns the shadow effect of a text |3 | |textTransform |Sets or returns the capitalization of a text |1 | |top |Sets or returns the top position of a positioned element |2 | |transform |Applies a 2D or 3D transformation to an element |3 | |transformOrigin |Sets or returns the position of transformed elements |3 | |transformStyle |Sets or returns how nested elements are rendered in 3D space |3 | |transition |A shorthand property for setting or returning the four transition properties |3 | |transitionProperty |Sets or returns the CSS property that the transition effect is for |3 | |transitionDuration |Sets or returns how many seconds or milliseconds a transition effect takes to complete |3 | |transitionTimingFunction |Sets or returns the speed curve of the transition effect |3 | |transitionDelay |Sets or returns when the transition effect will start |3 | |unicodeBidi |Sets or returns whether the text should be overridden to support multiple languages in the same document |2 | |userSelect |Sets or returns whether the text of an element can be selected or not |2 | |verticalAlign |Sets or returns the vertical alignment of the content in an element |1 | |visibility |Sets or returns whether an element should be visible |2 | |whiteSpace |Sets or returns how to handle tabs, line breaks and whitespace in a text |1 | |width |Sets or returns the width of an element |1 | |wordBreak |Sets or returns line breaking rules for non-CJK scripts |3 | |wordSpacing |Sets or returns the spacing between words in a text |1 | |wordWrap |Allows long, unbreakable words to be broken and wrap to the next line |3 | |widows |Sets or returns the minimum number of lines for an element that must be visible at the top of a page |2 | |zIndex |Sets or returns the stack order of a positioned element |2 | ### 访问样式对象 可以从文档的头部或特定的HTML元素访问Style对象。 - 从文档的头部访问样式对象: 例如: `var x = document.getElementsByTagName("STYLE");` - 访问指定元素的样式对象: 例 `var x = document.getElementById("myH1").style;` ### 创建样式对象 - 您可以使用`document.createElement()`方法创建<style>元素: 例 `var x = document.createElement("STYLE");` - 您还可以设置现有元素的样式属性: 例 `document.getElementById("myH1").style.color = "red";` ## `windows`窗口对象 窗口对象表示浏览器中打开的窗口。 如果文档包含框架(<iframe>标记),则浏览器将为HTML文档创建一个窗口对象,并为每个框架创建一个其他窗口对象。 注意:没有适用于`windows`对象的公共标准,但是所有主要的浏览器都支持它。 ### `windows`窗口对象属性 |Property |Description | | :----| :--------------| |closed |Returns a Boolean value indicating whether a window has been closed or not | |console |Returns a reference to the Console object, which provides methods for logging information to the browser's console (See Console object) | |defaultStatus |Sets or returns the default text in the statusbar of a window | |document |Returns the Document object for the window (See Document object) | |frameElement |Returns the \<iframe> element in which the current window is inserted | |frames |Returns all \<iframe> elements in the current window | |history |Returns the History object for the window (See History object) | |innerHeight |Returns the height of the window's content area (viewport) including scrollbars | |innerWidth |Returns the width of a window's content area (viewport) including scrollbars | |length |Returns the number of \<iframe> elements in the current window | |localStorage |Allows to save key/value pairs in a web browser. Stores the data with no expiration date | |location |Returns the Location object for the window (See Location object) | |name |Sets or returns the name of a window | |navigator |Returns the Navigator object for the window (See Navigator object) | |opener |Returns a reference to the window that created the window | |outerHeight |Returns the height of the browser window, including toolbars/scrollbars | |outerWidth |Returns the width of the browser window, including toolbars/scrollbars | |pageXOffset |Returns the pixels the current document has been scrolled (horizontally) from the upper left corner of the window | |pageYOffset |Returns the pixels the current document has been scrolled (vertically) from the upper left corner of the window | |parent |Returns the parent window of the current window | |screen |Returns the Screen object for the window (See Screen object) | |screenLeft |Returns the horizontal coordinate of the window relative to the screen | |screenTop |Returns the vertical coordinate of the window relative to the screen | |screenX |Returns the horizontal coordinate of the window relative to the screen | |screenY |Returns the vertical coordinate of the window relative to the screen | |sessionStorage |Allows to save key/value pairs in a web browser. Stores the data for one session | |scrollX |An alias of pageXOffset | |scrollY |An alias of pageYOffset | |self |Returns the current window | |status |Sets or returns the text in the statusbar of a window | |top |Returns the topmost browser window | ### `windows`窗口对象方法 |Method |Description | | :----| :------------| |alert() |Displays an alert box with a message and an OK button | |atob() |Decodes a base-64 encoded string | |blur() |Removes focus from the current window | |btoa() |Encodes a string in base-64 | |clearInterval() |Clears a timer set with setInterval() | |clearTimeout() |Clears a timer set with setTimeout() | |close() |Closes the current window | |confirm() |Displays a dialog box with a message and an OK and a Cancel button | |focus() |Sets focus to the current window | |getComputedStyle() |Gets the current computed CSS styles applied to an element | |getSelection() |Returns a Selection object representing the range of text selected by the user | |matchMedia() |Returns a MediaQueryList object representing the specified CSS media query string | |moveBy() |Moves a window relative to its current position | |moveTo() |Moves a window to the specified position | |open() |Opens a new browser window | |print() |Prints the content of the current window | |prompt() |Displays a dialog box that prompts the visitor for input | |requestAnimationFrame() |Requests the browser to call a function to update an animation before the next repaint | |resizeBy() |Resizes the window by the specified pixels | |resizeTo() |Resizes the window to the specified width and height | |scroll() |Deprecated. This method has been replaced by the scrollTo() method. | |scrollBy() |Scrolls the document by the specified number of pixels | |scrollTo() |Scrolls the document to the specified coordinates | |setInterval() |Calls a function or evaluates an expression at specified intervals (in milliseconds) | |setTimeout() |Calls a function or evaluates an expression after a specified number of milliseconds | |stop() |Stops the window from loading | -----------