From 218934fa2ed1c702a6d3923d2aa2cc6b43c48684 Mon Sep 17 00:00:00 2001 From: Peter Bengtsson Date: Tue, 8 Dec 2020 14:43:23 -0500 Subject: initial commit --- files/zh-tw/web/api/element/attributes/index.html | 121 ++++ files/zh-tw/web/api/element/classlist/index.html | 403 ++++++++++++ files/zh-tw/web/api/element/click_event/index.html | 205 +++++++ .../zh-tw/web/api/element/clientheight/index.html | 62 ++ .../zh-tw/web/api/element/getattribute/index.html | 71 +++ files/zh-tw/web/api/element/index.html | 674 +++++++++++++++++++++ files/zh-tw/web/api/element/innerhtml/index.html | 215 +++++++ .../web/api/element/insertadjacenthtml/index.html | 135 +++++ .../web/api/element/queryselectorall/index.html | 140 +++++ .../zh-tw/web/api/element/scrollheight/index.html | 170 ++++++ files/zh-tw/web/api/element/scrolltop/index.html | 73 +++ .../web/api/element/touchcancel_event/index.html | 169 ++++++ 12 files changed, 2438 insertions(+) create mode 100644 files/zh-tw/web/api/element/attributes/index.html create mode 100644 files/zh-tw/web/api/element/classlist/index.html create mode 100644 files/zh-tw/web/api/element/click_event/index.html create mode 100644 files/zh-tw/web/api/element/clientheight/index.html create mode 100644 files/zh-tw/web/api/element/getattribute/index.html create mode 100644 files/zh-tw/web/api/element/index.html create mode 100644 files/zh-tw/web/api/element/innerhtml/index.html create mode 100644 files/zh-tw/web/api/element/insertadjacenthtml/index.html create mode 100644 files/zh-tw/web/api/element/queryselectorall/index.html create mode 100644 files/zh-tw/web/api/element/scrollheight/index.html create mode 100644 files/zh-tw/web/api/element/scrolltop/index.html create mode 100644 files/zh-tw/web/api/element/touchcancel_event/index.html (limited to 'files/zh-tw/web/api/element') diff --git a/files/zh-tw/web/api/element/attributes/index.html b/files/zh-tw/web/api/element/attributes/index.html new file mode 100644 index 0000000000..ce24985c8b --- /dev/null +++ b/files/zh-tw/web/api/element/attributes/index.html @@ -0,0 +1,121 @@ +--- +title: Element.attributes +slug: Web/API/Element/attributes +translation_of: Web/API/Element/attributes +--- +

{{ APIRef("DOM") }}

+ +

 

+ +

The Element.attributes property returns a live collection of all attribute nodes registered to the specified node. It is a {{domxref("NamedNodeMap")}}, not an Array, so it has no {{jsxref("Array")}} methods and the {{domxref("Attr")}} nodes' indexes may differ among browsers. To be more specific, attributes is a key/value pair of strings that represents any information regarding that attribute.

+ +

 

+ +

Element.attribute 特性會把特定節點裡所有的屬性變成一個集合,然後回傳出來. 這是一個  NamedNodeMap, 而並非一個陣列. 所以它並沒有陣列的方法和在瀏覽器中  Attr節點裡的索引值也可能不同. 更詳細的來說, attributes 是一個鍵/值的配對, 它包含了所有有關於這個節點屬性的資訊

+ +

 

+ +

Syntax

+ +
var attr = element.attributes;
+
+ +

Example

+ +

Basic examples

+ +
// Get the first <p> element in the document
+var para = document.getElementsByTagName("p")[0];
+var atts = para.attributes;
+ +

Enumerating elements attributes

+ +

Numerical indexing is useful for going through all of an element's attributes.
+ The following example runs through the attribute nodes for the element in the document with id "paragraph", and prints each attribute's value.

+ +
<!DOCTYPE html>
+
+<html>
+
+ <head>
+  <title>Attributes example</title>
+  <script type="text/javascript">
+   function listAttributes() {
+     var paragraph = document.getElementById("paragraph");
+     var result = document.getElementById("result");
+
+     // First, let's verify that the paragraph has some attributes
+     if (paragraph.hasAttributes()) {
+       var attrs = paragraph.attributes;
+       var output = "";
+       for(var i = attrs.length - 1; i >= 0; i--) {
+         output += attrs[i].name + "->" + attrs[i].value;
+       }
+       result.value = output;
+     } else {
+       result.value = "No attributes to show";
+     }
+   }
+  </script>
+ </head>
+
+<body>
+ <p id="paragraph" style="color: green;">Sample Paragraph</p>
+ <form action="">
+  <p>
+    <input type="button" value="Show first attribute name and value"
+      onclick="listAttributes();">
+    <input id="result" type="text" value="">
+  </p>
+ </form>
+</body>
+</html>
+ +

Specifications

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM WHATWG', '#dom-element-attributes', 'Element.attributes')}}{{Spec2('DOM WHATWG')}}From {{SpecName('DOM3 Core')}}, moved from {{domxref("Node")}} to {{domxref("Element")}}
{{SpecName('DOM3 Core', 'core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM3 Core')}}No change from {{SpecName('DOM2 Core')}}
{{SpecName('DOM2 Core', 'core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM2 Core')}}No change from {{SpecName('DOM1')}}
{{SpecName('DOM1', 'level-one-core.html#ID-84CF096', 'Element.attributes')}}{{Spec2('DOM1')}}Initial definition.
+ +

Browser compatibility

+ + + +

{{Compat("api.Element.attributes")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/api/element/classlist/index.html b/files/zh-tw/web/api/element/classlist/index.html new file mode 100644 index 0000000000..afa5b7c862 --- /dev/null +++ b/files/zh-tw/web/api/element/classlist/index.html @@ -0,0 +1,403 @@ +--- +title: Element.classList +slug: Web/API/Element/classList +translation_of: Web/API/Element/classList +--- +
{{APIRef("DOM")}}
+ +

Element.classList 唯讀屬性代表了該元素所擁有之類別屬性(Class {{Glossary("Attribute")}})的即時更新集-{{domxref("DOMTokenList")}}。

+ +

使用 classList 屬性是取得元素 Class 的一種便利方式,也可以透過 {{domxref("element.className")}} 來得到以空格分隔之 Class 清單字串。

+ +

語法

+ +
var elementClasses = elementNodeReference.classList;
+
+ +

elementClasses is a {{domxref("DOMTokenList")}} representing the class attribute of elementNodeReference. If the class attribute was not set or is empty elementClasses.length returns 0. element.classList itself is read-only, although you can modify it using the add() and remove() methods.

+ +

方法

+ +
+
add( String [, String] )
+
Add specified class values. If these classes already exist in attribute of the element, then they are ignored.
+
remove( String [,String] )
+
Remove specified class values.
+
item ( Number )
+
Return class value by index in collection.
+
toggle ( String [, force] )
+
When only one argument is present: Toggle class value; i.e., if class exists then remove it and return false, if not, then add it and return true.
+ When a second argument is present: If the second argument is true, add specified class value, and if it is false, remove it.
+
contains( String )
+
Checks if specified class value exists in class attribute of the element.
+
+ +

範例

+ +
// div is an object reference to a <div> element with class="foo bar"
+div.classList.remove("foo");
+div.classList.add("anotherclass");
+
+// if visible is set remove it, otherwise add it
+div.classList.toggle("visible");
+
+//  add/remove visible, depending on test conditional, i less than 10
+div.classList.toggle("visible", i < 10 );
+
+alert(div.classList.contains("foo"));
+
+div.classList.add("foo","bar"); //add multiple classes
+ +
+

Versions of Firefox before 26 do not implement the use of several arguments in the add/remove/toggle methods. See https://bugzilla.mozilla.org/show_bug.cgi?id=814014

+
+ +

JavaScript shim for other implementations

+ +
Note: This shim does not work in Internet Explorer versions less than 8.
+ +
/*
+ * classList.js: Cross-browser full element.classList implementation.
+ * 2014-07-23
+ *
+ * By Eli Grey, http://eligrey.com
+ * Public Domain.
+ * NO WARRANTY EXPRESSED OR IMPLIED. USE AT YOUR OWN RISK.
+ */
+
+/*global self, document, DOMException */
+
+/*! @source http://purl.eligrey.com/github/classList.js/blob/master/classList.js*/
+
+if ("document" in self) {
+
+// Full polyfill for browsers with no classList support
+if (!("classList" in document.createElement("_"))) {
+
+(function (view) {
+
+"use strict";
+
+if (!('Element' in view)) return;
+
+var
+    classListProp = "classList"
+  , protoProp = "prototype"
+  , elemCtrProto = view.Element[protoProp]
+  , objCtr = Object
+  , strTrim = String[protoProp].trim || function () {
+    return this.replace(/^\s+|\s+$/g, "");
+  }
+  , arrIndexOf = Array[protoProp].indexOf || function (item) {
+    var
+        i = 0
+      , len = this.length
+    ;
+    for (; i < len; i++) {
+      if (i in this && this[i] === item) {
+        return i;
+      }
+    }
+    return -1;
+  }
+  // Vendors: please allow content code to instantiate DOMExceptions
+  , DOMEx = function (type, message) {
+    this.name = type;
+    this.code = DOMException[type];
+    this.message = message;
+  }
+  , checkTokenAndGetIndex = function (classList, token) {
+    if (token === "") {
+      throw new DOMEx(
+          "SYNTAX_ERR"
+        , "An invalid or illegal string was specified"
+      );
+    }
+    if (/\s/.test(token)) {
+      throw new DOMEx(
+          "INVALID_CHARACTER_ERR"
+        , "String contains an invalid character"
+      );
+    }
+    return arrIndexOf.call(classList, token);
+  }
+  , ClassList = function (elem) {
+    var
+        trimmedClasses = strTrim.call(elem.getAttribute("class") || "")
+      , classes = trimmedClasses ? trimmedClasses.split(/\s+/) : []
+      , i = 0
+      , len = classes.length
+    ;
+    for (; i < len; i++) {
+      this.push(classes[i]);
+    }
+    this._updateClassName = function () {
+      elem.setAttribute("class", this.toString());
+    };
+  }
+  , classListProto = ClassList[protoProp] = []
+  , classListGetter = function () {
+    return new ClassList(this);
+  }
+;
+// Most DOMException implementations don't allow calling DOMException's toString()
+// on non-DOMExceptions. Error's toString() is sufficient here.
+DOMEx[protoProp] = Error[protoProp];
+classListProto.item = function (i) {
+  return this[i] || null;
+};
+classListProto.contains = function (token) {
+  token += "";
+  return checkTokenAndGetIndex(this, token) !== -1;
+};
+classListProto.add = function () {
+  var
+      tokens = arguments
+    , i = 0
+    , l = tokens.length
+    , token
+    , updated = false
+  ;
+  do {
+    token = tokens[i] + "";
+    if (checkTokenAndGetIndex(this, token) === -1) {
+      this.push(token);
+      updated = true;
+    }
+  }
+  while (++i < l);
+
+  if (updated) {
+    this._updateClassName();
+  }
+};
+classListProto.remove = function () {
+  var
+      tokens = arguments
+    , i = 0
+    , l = tokens.length
+    , token
+    , updated = false
+    , index
+  ;
+  do {
+    token = tokens[i] + "";
+    index = checkTokenAndGetIndex(this, token);
+    while (index !== -1) {
+      this.splice(index, 1);
+      updated = true;
+      index = checkTokenAndGetIndex(this, token);
+    }
+  }
+  while (++i < l);
+
+  if (updated) {
+    this._updateClassName();
+  }
+};
+classListProto.toggle = function (token, force) {
+  token += "";
+
+  var
+      result = this.contains(token)
+    , method = result ?
+      force !== true && "remove"
+    :
+      force !== false && "add"
+  ;
+
+  if (method) {
+    this[method](token);
+  }
+
+  if (force === true || force === false) {
+    return force;
+  } else {
+    return !result;
+  }
+};
+classListProto.toString = function () {
+  return this.join(" ");
+};
+
+if (objCtr.defineProperty) {
+  var classListPropDesc = {
+      get: classListGetter
+    , enumerable: true
+    , configurable: true
+  };
+  try {
+    objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
+  } catch (ex) { // IE 8 doesn't support enumerable:true
+    if (ex.number === -0x7FF5EC54) {
+      classListPropDesc.enumerable = false;
+      objCtr.defineProperty(elemCtrProto, classListProp, classListPropDesc);
+    }
+  }
+} else if (objCtr[protoProp].__defineGetter__) {
+  elemCtrProto.__defineGetter__(classListProp, classListGetter);
+}
+
+}(self));
+
+} else {
+// There is full or partial native classList support, so just check if we need
+// to normalize the add/remove and toggle APIs.
+
+(function () {
+  "use strict";
+
+  var testElement = document.createElement("_");
+
+  testElement.classList.add("c1", "c2");
+
+  // Polyfill for IE 10/11 and Firefox <26, where classList.add and
+  // classList.remove exist but support only one argument at a time.
+  if (!testElement.classList.contains("c2")) {
+    var createMethod = function(method) {
+      var original = DOMTokenList.prototype[method];
+
+      DOMTokenList.prototype[method] = function(token) {
+        var i, len = arguments.length;
+
+        for (i = 0; i < len; i++) {
+          token = arguments[i];
+          original.call(this, token);
+        }
+      };
+    };
+    createMethod('add');
+    createMethod('remove');
+  }
+
+  testElement.classList.toggle("c3", false);
+
+  // Polyfill for IE 10 and Firefox <24, where classList.toggle does not
+  // support the second argument.
+  if (testElement.classList.contains("c3")) {
+    var _toggle = DOMTokenList.prototype.toggle;
+
+    DOMTokenList.prototype.toggle = function(token, force) {
+      if (1 in arguments && !this.contains(token) === !force) {
+        return force;
+      } else {
+        return _toggle.call(this, token);
+      }
+    };
+
+  }
+
+  testElement = null;
+}());
+
+}
+
+}
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName("HTML WHATWG", "dom.html#dom-classlist", "Element.classList")}}{{Spec2("HTML WHATWG")}}Note within the HTML specification related to the {{htmlattrxref("class")}} attribute.
{{SpecName("DOM WHATWG", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM WHATWG")}}Initial definition
{{SpecName("DOM4", "#dom-element-classlist", "Element.classList")}}{{Spec2("DOM4")}} 
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support8.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}}10[1]11.505.1
toggle method's second argument24{{CompatVersionUnknown}}{{CompatGeckoDesktop("24")}}{{CompatNo}}[2]155.1
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support3.0{{CompatGeckoMobile("1.9.2")}}1011.105.0
toggle method's second argument{{CompatUnknown}}{{CompatGeckoMobile("24")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
+
+ +

[1] Not supported for SVG elements.  See a report at Microsoft about that.
+ [2] Internet Explorer never implemented this. See a report at Microsoft about that.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/element/click_event/index.html b/files/zh-tw/web/api/element/click_event/index.html new file mode 100644 index 0000000000..4c7044e4b3 --- /dev/null +++ b/files/zh-tw/web/api/element/click_event/index.html @@ -0,0 +1,205 @@ +--- +title: click +slug: Web/API/Element/click_event +tags: + - 待翻譯 +translation_of: Web/API/Element/click_event +--- +

click 事件通常會在設備的按鈕(通常是滑鼠按鍵)點擊元素時執行。

+ +

基本資料

+ +
+
詳述
+
DOM L3
+
介面
+
{{domxref("MouseEvent")}}
+
Bubbles
+
Yes
+
Cancelable
+
Yes
+
Target
+
網頁元素
+
Default Action
+
Varies
+
+ +

Properties

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not?
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)A count of consecutive clicks that happened in a short amount of time, incremented by one.
currentTarget {{readonlyInline}}EventTargetThe node that had the event listener attached.
relatedTarget {{readonlyInline}}EventTargetFor mouseover, mouseout, mouseenter and mouseleave events: the target of the complementary event (the mouseleave target in the case of a mouseenter event). null otherwise.
screenX {{readonlyInline}}longThe X coordinate of the mouse pointer in global (screen) coordinates.
screenY {{readonlyInline}}longThe Y coordinate of the mouse pointer in global (screen) coordinates.
clientX {{readonlyInline}}longThe X coordinate of the mouse pointer in local (DOM content) coordinates.
clientY {{readonlyInline}}longThe Y coordinate of the mouse pointer in local (DOM content) coordinates.
button {{readonlyInline}}unsigned shortThe button number that was pressed when the mouse event was fired: Left button=0, middle button=1 (if present), right button=2. For mice configured for left handed use in which the button actions are reversed the values are instead read from right to left.
buttons {{readonlyInline}}unsigned shortThe buttons being pressed when the mouse event was fired: Left button=1, Right button=2, Middle (wheel) button=4, 4th button (typically, "Browser Back" button)=8, 5th button (typically, "Browser Forward" button)=16. If two or more buttons are pressed, returns the logical sum of the values. E.g., if Left button and Right button are pressed, returns 3 (=1 | 2). More info.
mozPressure {{readonlyInline}}floatThe amount of pressure applied to a touch or tabdevice when generating the event; this value ranges between 0.0 (minimum pressure) and 1.0 (maximum pressure).
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

範例

+ +
<div id="test"></div>
+
+<script>
+  document.getElementById("test").addEventListener("click", function( event ) {
+    // 在 “clicked div”顯示點擊次數
+    event.target.innerHTML = "click count: " + event.detail;
+  }, false);
+</script>
+
+ +

Browser compatibility

+ +

Internet Explorer

+ +

Internet Explorer 8 & 9 suffer from a bug where elements with a computed {{cssxref("background-color")}} of transparent that are overlaid on top of other element(s) won't receive click events. Any click events will be fired at the underlying element(s) instead. See this live example for a demonstration.

+ +

Known workarounds for this bug:

+ + + +

Safari Mobile

+ +

Safari Mobile 7.0+ (and likely earlier versions too) suffers from a bug where click events aren't fired on elements that aren't typically interactive (e.g. {{HTMLElement("div")}}) and which also don't have event listeners directly attached to the elements themselves (i.e. event delegation is being used). See this live example for a demonstration. See also Safari's docs on making elements clickable and the definition of "clickable element".

+ +

Known workarounds for this bug:

+ + + +

Safari Mobile considers the following elements to be typically interactive (and thus they aren't affected by this bug):

+ + + +

關聯事件

+ + diff --git a/files/zh-tw/web/api/element/clientheight/index.html b/files/zh-tw/web/api/element/clientheight/index.html new file mode 100644 index 0000000000..99ae4faf06 --- /dev/null +++ b/files/zh-tw/web/api/element/clientheight/index.html @@ -0,0 +1,62 @@ +--- +title: Element.clientHeight +slug: Web/API/Element/clientHeight +tags: + - API + - Reference +translation_of: Web/API/Element/clientHeight +--- +

{{ APIRef("DOM") }}

+ +

Element.clientHeight 唯讀屬性會回傳元素內部高度(像素),包含 padding 但並未包含水平滾動條、border、margin。

+ +

clientHeight 可以被計算成 CSS height + CSS padding - 水平滾動條的高度(如果有顯示)

+ +
+

Note: 這個屬性會以四捨五入進位取整數. 如果要使用非整數值, 使用 {{ domxref("element.getBoundingClientRect()") }}.

+
+ +

表達式

+ +
var h = element.clientHeight;
+ +

h 代表元素高度(pixels)的正整數.

+ +

範例

+ +

 

+ +

             Image:Dimensions-client.png

+ + +

規範

+ + + + + + + + + + + + + + + + +
規範狀態
{{SpecName('CSSOM View', '#dom-element-clientheight', 'clientHeight')}}{{Spec2('CSSOM View')}} 
+ +

+ +

clientHeight 是在 the Internet Explorer 物件介紹的屬性.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/element/getattribute/index.html b/files/zh-tw/web/api/element/getattribute/index.html new file mode 100644 index 0000000000..e5b7a1c27e --- /dev/null +++ b/files/zh-tw/web/api/element/getattribute/index.html @@ -0,0 +1,71 @@ +--- +title: Element.getAttribute() +slug: Web/API/Element/getAttribute +translation_of: Web/API/Element/getAttribute +--- +
{{APIRef("DOM")}}
+ +

摘要

+ +

getAttribute() 函式會回傳該網頁元素的屬性。 如果該屬性不存在,其回傳值會是null或 "" (空字串); 詳見 {{Anch("Notes")}} 。

+ +

語法

+ +
var attribute = element.getAttribute(attributeName);
+
+ +

where

+ + + +

Example

+ +
var div1 = document.getElementById("div1");
+var align = div1.getAttribute("align");
+
+alert(align); // shows the value of align for the element with id="div1"
+ +

Notes

+ +

When called on an HTML element in a DOM flagged as an HTML document, getAttribute() lower-cases its argument before proceeding.

+ +

Essentially all web browsers (Firefox, Internet Explorer, recent versions of Opera, Safari, Konqueror, and iCab, as a non-exhaustive list) return null when the specified attribute does not exist on the specified element and this is what the current DOM specification draft specifies. The old DOM 3 Core specification, on the other hand, says that the correct return value in this case is actually the empty string, and some DOM implementations implement this behavior. The implementation of getAttribute in XUL (Gecko) actually follows the DOM 3 Core specification and returns an empty string. Consequently, you should use {{domxref("element.hasAttribute()")}} to check for an attribute's existence prior to calling getAttribute() if it is possible that the requested attribute does not exist on the specified element.

+ +

Browser compatibility

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari
Basic support2923{{CompatVersionUnknown}}{{CompatVersionUnknown}}6
+
+ +
{{DOMAttributeMethods}}
+ +

Specification

+ + diff --git a/files/zh-tw/web/api/element/index.html b/files/zh-tw/web/api/element/index.html new file mode 100644 index 0000000000..d363baeead --- /dev/null +++ b/files/zh-tw/web/api/element/index.html @@ -0,0 +1,674 @@ +--- +title: Element +slug: Web/API/Element +tags: + - API + - DOM + - DOM Reference + - Element + - NeedsTranslation + - TopicStub + - Élément(2) +translation_of: Web/API/Element +--- +

{{ APIRef("DOM") }}

+ +

Element 介面表示了一個在 {{domxref("Document")}} 中的物件,其描述了各類型元素的共同屬性與方法,Element 的子介面則定義了不同類型元素的具體行為並增加額外的功能。例如 {{domxref("HTMLElement")}} 為所有 HTML 元素的基礎介面,而 {{domxref("SVGElement")}} 則是定義所有 SVG 元素的介面。

+ +

在 Web 領域之外,如 XUL 語言也能藉由 XULElement 介面來繼承 Element

+ +

{{InheritanceDiagram}}

+ +

屬性

+ +

Inherits properties from its parent interface, {{domxref("Node")}}, and by extension that interface's parent, {{domxref("EventTarget")}}. It implements the properties of {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, and {{domxref("Animatable")}}.

+ +
+
{{ domxref("Element.assignedSlot")}} {{experimental_inline}} {{readOnlyInline}}
+
Returns the {{domxref("HTMLSlotElement")}} interface associated with the element.
+
{{ domxref("Element.attributes") }} {{readOnlyInline}}
+
Returns a {{ domxref("NamedNodeMap") }} object containing the assigned attributes of the corresponding HTML element.
+
{{ domxref("Element.classList") }} {{readOnlyInline}}
+
Returns a {{ domxref("DOMTokenList") }} containing the list of class attributes.
+
{{ domxref("Element.className") }}
+
Is a {{domxref("DOMString")}} representing the class of the element.
+
{{ domxref("Element.clientHeight") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the inner height of the element.
+
{{ domxref("Element.clientLeft") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the width of the left border of the element.
+
{{ domxref("Element.clientTop") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the width of the top border of the element.
+
{{ domxref("Element.clientWidth") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the inner width of the element.
+
{{domxref("Element.computedName")}} {{readOnlyInline}}
+
Returns a {{domxref("DOMString")}} containing the label exposed to accessibility.
+
{{domxref("Element.computedRole")}} {{readOnlyInline}}
+
Returns a {{domxref("DOMString")}} containing the ARIA role that has been applied to a particular element.
+
{{ domxref("Element.id") }}
+
Is a {{domxref("DOMString")}} representing the id of the element.
+
{{ domxref("Element.innerHTML") }}
+
Is a {{domxref("DOMString")}} representing the markup of the element's content.
+
{{ domxref("Element.localName") }} {{readOnlyInline}}
+
A {{domxref("DOMString")}} representing the local part of the qualified name of the element.
+
{{domxref("Element.namespaceURI")}} {{readonlyInline}}
+
The namespace URI of the element, or null if it is no namespace. +
+

Note: In Firefox 3.5 and earlier, HTML elements are in no namespace. In later versions, HTML elements are in the http://www.w3.org/1999/xhtml namespace in both HTML and XML trees. {{ gecko_minversion_inline("1.9.2") }}

+
+
+
{{ domxref("NonDocumentTypeChildNode.nextElementSibling") }} {{readOnlyInline}}
+
Is a {{ domxref("Element") }}, the element immediately following the given one in the tree, or null if there's no sibling node.
+
{{ domxref("Element.outerHTML") }} {{experimental_inline}}
+
Is a {{domxref("DOMString")}} representing the markup of the element including its content. When used as a setter, replaces the element with nodes parsed from the given string.
+
{{ domxref("Element.prefix") }} {{readOnlyInline}}
+
A {{domxref("DOMString")}} representing the namespace prefix of the element, or null if no prefix is specified.
+
{{ domxref("NonDocumentTypeChildNode.previousElementSibling") }} {{readOnlyInline}}
+
Is a {{ domxref("Element") }}, the element immediately preceding the given one in the tree, or null if there is no sibling element.
+
{{ domxref("Element.scrollHeight") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the scroll view height of an element.
+
{{ domxref("Element.scrollLeft") }} {{experimental_inline}}
+
Is a {{jsxref("Number")}} representing the left scroll offset of the element.
+
{{ domxref("Element.scrollLeftMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the maximum left scroll offset possible for the element.
+
{{ domxref("Element.scrollTop") }} {{experimental_inline}}
+
Is a {{jsxref("Number")}} representing the top scroll offset the an element.
+
{{ domxref("Element.scrollTopMax") }} {{non-standard_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the maximum top scroll offset possible for the element.
+
{{ domxref("Element.scrollWidth") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns a {{jsxref("Number")}} representing the scroll view width of the element.
+
{{domxref("Element.shadowRoot") }} {{experimental_inline}} {{readOnlyInline}}
+
Returns the youngest shadow root that is hosted by the element.
+
{{domxref("Element.slot")}} {{experimental_inline}}
+
Returns the name of the shadow DOM slot attatched to the element. A slot is a placeholder inside a web component that users can fill with their own markup.
+
{{domxref("Element.tabStop")}} {{non-standard_inline}}
+
Is a {{jsxref("Boolean")}} indicating if the element can receive input focus via the tab key.
+
{{ domxref("Element.tagName") }} {{readOnlyInline}}
+
Returns a {{domxref("String")}} with the name of the tag for the given element.
+
{{ domxref("Element.undoManager")}} {{experimental_inline}} {{readOnlyInline}}
+
Returns the {{domxref("UndoManager")}} associated with the element.
+
{{ domxref("Element.undoScope")}} {{experimental_inline}}
+
Is a {{jsxref("Boolean")}} indicating if the element is an undo scope host, or not.
+
+ +
+

Note: DOM Level 3 defined namespaceURI, localName and prefix on the {{domxref("Node")}} interface. In DOM4 they were moved to Element.

+ +

This change is implemented in Chrome since version 46.0 and Firefox since version 48.0.

+
+ +

事件處理器

+ +
+
{{ domxref("Element.ongotpointercapture") }}
+
Returns the event handler for the {{event("gotpointercapture")}} event type.
+
{{ domxref("Element.onlostpointercapture") }}
+
Returns the event handler for the {{event("lostpointercapture")}} event type.
+
{{ domxref("Element.onwheel") }} {{ non-standard_inline() }}
+
Returns the event handling code for the wheel event.
+
+ +

方法

+ +

Inherits methods from its parents {{domxref("Node")}}, and its own parent, {{domxref("EventTarget")}}, and implements those of {{domxref("ParentNode")}}, {{domxref("ChildNode")}}, {{domxref("NonDocumentTypeChildNode")}}, and {{domxref("Animatable")}}.

+ +
+
{{ domxref("EventTarget.addEventListener()") }}
+
Registers an event handler to a specific event type on the element.
+
{{domxref("Element.attachShadow()")}} {{experimental_inline}}
+
Attatches a shadow DOM tree to the specified element and returns a reference to its {{domxref("ShadowRoot")}}.
+
{{domxref("Element.animate()")}} {{experimental_inline}}
+
A shortcut method to create and run an animation on an element. Returns the created Animation object instance.
+
{{ domxref("Element.closest()")}} {{experimental_inline}}
+
Returns the {{domxref("Element")}}, descendant of this element (or this element itself), that is the closest ancestor of the elements selected by the selectors given in parameter.
+
{{ domxref("Element.createShadowRoot()")}} {{experimental_inline}} {{deprecated_inline()}}
+
Creates a shadow DOM on on the element, turning it into a shadow host. Returns a {{domxref("ShadowRoot")}}.
+
{{ domxref("EventTarget.dispatchEvent()") }}
+
Dispatches an event to this node in the DOM and returns a {{jsxref("Boolean")}} that indicates that at least one handler has not canceled it.
+
{{domxref("Element.find()")}}{{experimental_inline}}
+
...
+
{{domxref("Element.findAll()")}}{{experimental_inline}}
+
...
+
{{domxref("Element.getAnimations()")}} {{experimental_inline}}
+
Returns an array of Animation objects currently active on the element.
+
{{ domxref("Element.getAttribute()") }}
+
Retrieves the value of the named attribute from the current node and returns it as an {{jsxref("Object")}}.
+
{{ domxref("Element.getAttributeNames()") }}
+
 
+
{{ domxref("Element.getAttributeNS()") }}
+
Retrieves the value of the attribute with the specified name and namespace, from the current node and returns it as an {{jsxref("Object")}}.
+
{{ domxref("Element.getAttributeNode()") }} {{obsolete_inline}}
+
Retrieves the node representation of the named attribute from the current node and returns it as an {{ domxref("Attr") }}.
+
{{ domxref("Element.getAttributeNodeNS()") }} {{obsolete_inline}}
+
Retrieves the node representation of the attribute with the specified name and namespace, from the current node and returns it as an {{ domxref("Attr") }}.
+
{{ domxref("Element.getBoundingClientRect()") }}
+
...
+
{{ domxref("Element.getClientRects()") }}
+
Returns a collection of rectangles that indicate the bounding rectangles for each line of text in a client.
+
{{domxref("Element.getDestinationInsertionPoints()")}} {{experimental_inline}}
+
+
{{ domxref("Element.getElementsByClassName()") }}
+
Returns a live {{ domxref("HTMLCollection") }} that contains all descendants of the current element that possess the list of classes given in the parameter.
+
{{ domxref("Element.getElementsByTagName()") }}
+
Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name, from the current element.
+
{{ domxref("Element.getElementsByTagNameNS()") }}
+
Returns a live {{ domxref("HTMLCollection") }} containing all descendant elements, of a particular tag name and namespace, from the current element.
+
{{ domxref("Element.hasAttribute()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute or not.
+
{{ domxref("Element.hasAttributeNS()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has the specified attribute, in the specified namespace, or not.
+
{{ domxref("Element.hasAttributes()") }}
+
Returns a {{jsxref("Boolean")}} indicating if the element has one or more HTML attributes present.
+
{{ domxref("Element.insertAdjacentElement") }} {{experimental_inline}}
+
Inserts a given element node at a given position relative to the element it is invoked upon.
+
{{ domxref("Element.insertAdjacentHTML") }} {{experimental_inline}}
+
Parses the text as HTML or XML and inserts the resulting nodes into the tree in the position given.
+
{{ domxref("Element.insertAdjacentText") }} {{experimental_inline}}
+
Inserts a given text node at a given position relative to the element it is invoked upon.
+
{{ domxref("Element.matches()") }} {{experimental_inline}}
+
Returns a {{jsxref("Boolean")}} indicating whether or not the element would be selected by the specified selector string.
+
{{ domxref("Element.querySelector()") }}
+
Returns the first {{ domxref("Node") }} which matches the specified selector string relative to the element.
+
{{ domxref("Element.querySelectorAll") }}
+
Returns a {{ domxref("NodeList") }} of nodes which match the specified selector string relative to the element.
+
{{ domxref("Element.releasePointerCapture")}}
+
Releases (stops) pointer capture that was previously set for a specific {{domxref("PointerEvent","pointer event")}}.
+
{{domxref("ChildNode.remove()")}} {{experimental_inline}}
+
Removes the element from the children list of its parent.
+
{{ domxref("Element.removeAttribute()") }}
+
Removes the named attribute from the current node.
+
{{ domxref("Element.removeAttributeNS()") }}
+
Removes the attribute with the specified name and namespace, from the current node.
+
{{ domxref("Element.removeAttributeNode()") }} {{obsolete_inline}}
+
Removes the node representation of the named attribute from the current node.
+
{{ domxref("EventTarget.removeEventListener()") }}
+
Removes an event listener from the element.
+
{{ domxref("Element.requestFullscreen()") }} {{experimental_inline}}
+
Asynchronously asks the browser to make the element full-screen.
+
{{ domxref("Element.requestPointerLock()")}} {{experimental_inline}}
+
Allows to asynchronously ask for the pointer to be locked on the given element.
+
+ +
+
{{ domxref("Element.scrollIntoView()") }} {{experimental_inline}}
+
Scrolls the page until the element gets into the view.
+
{{ domxref("Element.setAttribute()") }}
+
Sets the value of a named attribute of the current node.
+
{{ domxref("Element.setAttributeNS()") }}
+
Sets the value of the attribute with the specified name and namespace, from the current node.
+
{{ domxref("Element.setAttributeNode()") }} {{obsolete_inline}}
+
Sets the node representation of the named attribute from the current node.
+
{{ domxref("Element.setAttributeNodeNS()") }} {{obsolete_inline}}
+
Setw the node representation of the attribute with the specified name and namespace, from the current node.
+
{{ domxref("Element.setCapture()") }} {{non-standard_inline}}
+
Sets up mouse event capture, redirecting all mouse events to this element.
+
{{domxref("Element.setPointerCapture()")}}
+
Designates a specific element as the capture target of future {{domxref("PointerEvent","pointer events")}}.
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('Shadow DOM')}}{{Spec2('Shadow DOM')}} 
{{SpecName("Web Animations", '', '')}}{{Spec2("Web Animations")}}Added the getAnimations() method.
{{SpecName('Undo Manager', '', 'Element')}}{{Spec2('Undo Manager')}}Added the undoScope and undoManager properties.
{{SpecName('Pointer Events 2', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('Pointer Events 2')}}Added the following event handlers: ongotpointercapture and onlostpointercapture.
+ Added the following methods: setPointerCapture() and releasePointerCapture().
{{SpecName('Pointer Events', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('Pointer Events')}}Added the following event handlers: ongotpointercapture and onlostpointercapture.
+ Added the following methods: setPointerCapture() and releasePointerCapture().
{{SpecName('Selectors API Level 2', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 2')}}Added the following methods: matches() (implemented as mozMatchesSelector()), find(), findAll().
{{SpecName('Selectors API Level 1', '#interface-definitions', 'Element')}}{{Spec2('Selectors API Level 1')}}Added the following methods: querySelector() and querySelectorAll().
{{SpecName('Pointer Lock', 'index.html#element-interface', 'Element')}}{{Spec2('Pointer Lock')}}Added the requestPointerLock() method.
{{SpecName('Fullscreen', '#api', 'Element')}}{{Spec2('Fullscreen')}}Added the requestFullscreen() method.
{{SpecName('DOM Parsing', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('DOM Parsing')}}Added the following properties: innerHTML, and outerHTML.
+ Added the following method: insertAdjacentHTML().
{{SpecName('CSSOM View', '#extensions-to-the-element-interface', 'Element')}}{{Spec2('CSSOM View')}}Added the following properties: scrollTop, scrollLeft, scrollWidth, scrollHeight, clientTop, clientLeft, clientWidth, and clientHeight.
+ Added the following methods: getClientRects(), getBoundingClientRect(), and scrollIntoView().
{{SpecName('Element Traversal', '#ecmascript-bindings', 'Element')}}{{Spec2('Element Traversal')}}Added inheritance of the {{domxref("ElementTraversal")}} interface.
{{SpecName('DOM WHATWG', '#interface-element', 'Element')}}{{Spec2('DOM WHATWG')}}Removed the following methods: closest(), setIdAttribute(), setIdAttributeNS(), and setIdAttributeNode().
+ Removed the schemaTypeInfo property.
+ Modified the return value of getElementsByTag() and getElementsByTagNS().
+ Moved hasAttributes() from the Node interface to this one.
+ Inserted insertAdjacentElement() and insertAdjacentText().
{{SpecName('DOM3 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM3 Core')}}Added the following methods: setIdAttribute(), setIdAttributeNS(), and setIdAttributeNode(). These methods were never implemented and have been removed in later specifications.
+ Added the schemaTypeInfo property. This property was never implemented and has been removed in later specifications.
{{SpecName('DOM2 Core', 'core.html#ID-745549614', 'Element')}}{{Spec2('DOM2 Core')}}The normalize() method has been moved to {{domxref("Node")}}.
{{SpecName('DOM1', 'level-one-core.html#ID-745549614', 'Element')}}{{Spec2('DOM1')}}Initial definition.
+ +

瀏覽器相容性

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureChromeEdgeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0
children{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}7.0 with a significant bug [1]
+ 9.0 according to the spec
{{CompatVersionUnknown}}{{CompatNo}}
childElementCount, nextElementSibling, previousElementSibling{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
firstElementChild, lastElementChild{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}9.0{{CompatVersionUnknown}}{{CompatVersionUnknown}}
classList{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.2")}} {{CompatVersionUnknown}}{{CompatVersionUnknown}}
outerHTML {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("11")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
clientLeft, clientTop {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
getBoundingClientRect(), getClientRects() {{experimental_inline}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
querySelector(), querySelectorAll()1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}8.010.03.2 (525.3)
insertAdjacentHTML() {{experimental_inline}}1.0{{CompatVersionUnknown}}{{CompatGeckoDesktop("8")}}4.07.04.0 (527)
setCapture() {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("2")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
oncopy, oncut, onpaste {{non-standard_inline}}{{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("1.9")}}{{CompatVersionUnknown}} {{CompatNo}}
onwheel {{non-standard_inline}}{{CompatNo}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("17")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
ongotpointercapture, onlostpointercapture, setPointerCapture(), and releasePointerCapture(){{CompatChrome(52.0)}} [4]{{CompatVersionUnknown}}{{CompatVersionUnknown}} [3]10.0{{CompatNo}}{{CompatNo}}
matches() {{experimental_inline}}{{CompatVersionUnknown}} with the non-standard name webkitMatchesSelector{{CompatVersionUnknown}} {{property_prefix("webkit")}} {{property_prefix("ms")}}{{CompatGeckoDesktop("1.9.2")}} with the non-standard name mozMatchesSelector
+ {{CompatGeckoDesktop("34")}} with the standard name
9.0 with the non-standard name msMatchesSelector11.5 with the non-standard name oMatchesSelector
+ 15.0 with the non-standard name webkitMatchesSelector
5.0 with the non-standard name webkitMatchesSelector
find() and findAll(){{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
requestPointerLock()16.0 {{property_prefix("webkit")}}, behind an about:flags
+ 22.0 {{property_prefix("webkit")}} (with special cases, progressively lifted see [2])
{{CompatVersionUnknown}}{{CompatGeckoDesktop("14")}}{{property_prefix("moz")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
requestFullscreen()14.0 {{property_prefix("webkit")}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("10")}} {{property_prefix("moz")}}11.0 {{property_prefix("ms")}}12.10
+ 15.0 {{property_prefix("webkit")}}
5.1 {{property_prefix("webkit")}}
undoManager and undoScope{{CompatNo}}{{CompatNo}}{{CompatVersionUnknown}} (behind the dom.undo_manager.enabled pref){{CompatNo}}{{CompatNo}}{{CompatNo}}
attributes{{CompatUnknown}}{{CompatNo}}{{CompatGeckoDesktop("22")}}
+ Before this it was available via the {{domxref("Node")}} interface that any element inherits.
{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
scrollTopMax() and scrollLeftMax(){{CompatNo}}{{CompatNo}}{{CompatGeckoDesktop("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
closest(){{CompatUnknown}}{{CompatVersionUnknown}}{{CompatGeckoDesktop("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
hasAttributes(){{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("1.0")}} (on the {{domxref("Node")}} interface)
+ {{CompatGeckoDesktop("35")}} (on this interface
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
insertAdjacentElement(), insertAdjacentText(){{CompatVersionUnknown}}{{CompatNo}}{{CompatGeckoDesktop("48.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
assignedSlot, attatchShadow, shadowRoot, and slot{{CompatChrome(53)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}
computedRole and computedName{{CompatChrome(41)}}[4]{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}28[4]{{CompatUnknown}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewEdgeFirefox Mobile (Gecko)IE PhoneOpera MobileSafari MobileChrome for Android
Basic support1.0 {{CompatVersionUnknown}}{{CompatGeckoMobile("1")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}1.0 
scrollTopMax() and scrollLeftMax(){{CompatNo}} {{CompatNo}}{{CompatGeckoMobile("16")}}{{CompatNo}}{{CompatNo}}{{CompatNo}} 
closest(){{CompatUnknown}} {{CompatVersionUnknown}}{{CompatGeckoMobile("35")}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}} 
hasAttributes(){{CompatVersionUnknown}} {{CompatNo}}{{CompatGeckoMobile("1.0")}} (on the {{domxref("Node")}} interface)
+ {{CompatGeckoMobile("35")}} (on this interface
{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}} 
insertAdjacentElement(), insertAdjacentText(){{CompatVersionUnknown}} {{CompatVersionUnknown}}{{CompatGeckoMobile("48.0")}}{{CompatUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}} 
assignedSlot, attatchShadow, shadowRoot, and slot{{CompatNo}}{{CompatChrome(53.0)}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}{{CompatChrome(53)}}
computedRole and computedName{{CompatNo}}{{CompatNo}}{{CompatUnknown}}{{CompatUnknown}}{{CompatUnknown}}28[4]{{CompatUnknown}}{{CompatNo}}
+
+ +

[1] Internet Explorer 7 and 8 incorrectly return the comments as part of the children of an Element. This is fixed in Internet Explorer 9 and later.

+ +

[2] Chrome 16 allowed webkitRequestPointerLock() only in fullscreen; Chrome 21 for trusted web site (permission asked); Chrome 22 allowed it by default for all same-origin document; Chrome 23 allowed it in sandboxed {{HTMLElement("iframe")}} if the non-standard value webkit-allow-pointer-lock is set to the {{htmlattrxref("sandbox", "iframe")}} attribute.

+ +

[3] Implementation withdrawn. See {{Bug("1166347")}}.

+ +

[4] Behind a flag.

diff --git a/files/zh-tw/web/api/element/innerhtml/index.html b/files/zh-tw/web/api/element/innerhtml/index.html new file mode 100644 index 0000000000..df002176e4 --- /dev/null +++ b/files/zh-tw/web/api/element/innerhtml/index.html @@ -0,0 +1,215 @@ +--- +title: Element.innerHTML +slug: Web/API/Element/innerHTML +tags: + - 元素組件 + - 注譯 + - 裏HTML + - 裏超文本 +translation_of: Web/API/Element/innerHTML +--- +
{{APIRef("DOM")}}
+ + + +

 Element  的「innerHTML」屬性獲取或設置元素中包含的HTML或XML標記。

+ +
Note:  如{{HTMLElement("div")}}, {{HTMLElement("span")}}, or {{HTMLElement("noembed")}} 節點有包含字符(&),(<)或(>),innerHTML分別地回傳這些字符成為HTML的“&” “<” “>” 。 使用 Node.textContent 得到的這些文本節點的內容的原始拷貝件。
+ +

To insert the HTML into the document rather than replace the contents of an element, use the method {{domxref("Element.insertAdjacentHTML", "insertAdjacentHTML()")}}.

+ +

Syntax

+ +
const content = element.innerHTML;
+
+element.innerHTML = htmlString;
+
+ +

Value

+ +

A {{domxref("DOMString")}} containing the HTML serialization of the element's descendants. Setting the value of innerHTML removes all of the element's descendants and replaces them with nodes constructed by parsing the HTML given in the string htmlString.

+ +

Exceptions

+ +
+
SyntaxError
+
An attempt was made to set the value of innerHTML using a string which is not properly-formed HTML.
+
NoModificationAllowedError
+
An attempt was made to insert the HTML into a node whose parent is a {{domxref("Document")}}.
+
+ +

Usage notes

+ +

The innerHTML property can be used to examine the current HTML source of the page, including any changes that have been made since the page was initially loaded.

+ +

Reading the HTML contents of an element

+ +

Reading innerHTML causes the user agent to serialize the HTML or XML fragment comprised of the elment's descendants. The resulting string is returned.

+ +
let contents = myElement.innerHTML;
+ +

This lets you look at the HTML markup of the element's content nodes.

+ +
+

Note: The returned HTML or XML fragment is generated based on the current contents of the element, so the markup and formatting of the returned fragment is likely not to match the original page markup.

+
+ +
+

Note:基於元素的當前內容產生返回的HTML或XML片段,所以返回的片段的標記和格式可能不匹配原始頁面標記。

+
+ +

Replacing the contents of an element

+ +

Setting the value of innerHTML lets you easily replace the existing contents of an element with new content.

+ +

For example, you can erase the entire contents of a document by clearing the contents of the document's {{domxref("Document.body", "body")}} attribute:

+ +
document.body.innerHTML = "";
+ +

This example fetches the document's current HTML markup and replaces the "<" characters with the HTML entity "&lt;", thereby essentially converting the HTML into raw text. This is then wrapped in a {{HTMLElement("pre")}} element. Then the value of innerHTML is changed to this new string. As a result, the document contents are replaced with a display of the page's entire source code.

+ +
document.documentElement.innerHTML = "<pre>" +
+         document.documentElement.innerHTML.replace(/</g,"&lt;") +
+            "</pre>";
+ +

Operational details

+ +

What exactly happens when you set value of innerHTML? Doing so causes the user agent to follow these steps:

+ +
    +
  1. The specified value is parsed as HTML or XML (based on the document type), resulting in a {{domxref("DocumentFragment")}} object representing the new set of DOM nodes for the new elements.
  2. +
  3. If the element whose contents are being replaced is a {{HTMLElement("template")}} element, then the <template> element's {{domxref("HTMLTemplateElement.content", "content")}} attribute is replaced with the new DocumentFragment created in step 1.
  4. +
  5. For all other elements, the element's contents are replaced with the nodes in the new DocumentFragment.
  6. +
+ +

Security considerations

+ +

It is not uncommon to see innerHTML used to insert text into a web page. There is potential for this to become an attack vector on a site, creating a potential security risk.

+ +
const name = "John";
+// assuming 'el' is an HTML DOM element
+el.innerHTML = name; // harmless in this case
+
+// ...
+
+name = "<script>alert('I am John in an annoying alert!')</script>";
+el.innerHTML = name; // harmless in this case
+ +

Although this may look like a {{interwiki("wikipedia", "cross-site scripting")}} attack, the result is harmless. HTML5 specifies that a {{HTMLElement("script")}} tag inserted with innerHTML should not execute.

+ +

However, there are ways to execute JavaScript without using {{HTMLElement("script")}} elements, so there is still a security risk whenever you use innerHTML to set strings over which you have no control. For example:

+ +
const name = "<img src='x' onerror='alert(1)'>";
+el.innerHTML = name; // shows the alert
+ +

For that reason, it is recommended that you do not use innerHTML when inserting plain text; instead, use {{domxref("Node.textContent")}}. This doesn't parse the passed content as HTML, but instead inserts it as raw text.

+ +
+

Warning: If your project is one that will undergo any form of security review, using innerHTML most likely will result in your code being rejected. For example, if you use innerHTML in a browser extension and submit the extension to addons.mozilla.org, it will not pass the automated review process.

+
+ +

Example

+ +

This example uses innerHTML to create a mechanism for logging messages into a box on a web page.

+ +

JavaScript

+ +
function log(msg) {
+  var logElem = document.querySelector(".log");
+
+  var time = new Date();
+  var timeStr = time.toLocaleTimeString();
+  logElem.innerHTML += timeStr + ": " + msg + "<br/>";
+}
+
+log("Logging mouse events inside this container...");
+
+ +

The log() function creates the log output by getting the current time from a {{jsxref("Date")}} object using {{jsxref("Date.toLocaleTimeString", "toLocaleTimeString()")}}, and building a string with the timestamp and the message text. Then the message is appended to the box with the class "log".

+ +

We add a second method that logs information about {{domxref("MouseEvent")}} based events (such as {{event("mousedown")}}, {{event("click")}}, and {{event("mouseenter")}}):

+ +
function logEvent(event) {
+  var msg = "Event <strong>" + event.type + "</strong> at <em>" +
+            event.clientX + ", " + event.clientY + "</em>";
+  log(msg);
+}
+ +

Then we use this as the event handler for a number of mouse events on the box that contains our log:

+ +
var boxElem = document.querySelector(".box");
+
+boxElem.addEventListener("mousedown", logEvent);
+boxElem.addEventListener("mouseup", logEvent);
+boxElem.addEventListener("click", logEvent);
+boxElem.addEventListener("mouseenter", logEvent);
+boxElem.addEventListener("mouseleave", logEvent);
+ +

HTML

+ +

The HTML is quite simple for our example.

+ +
<div class="box">
+  <div><strong>Log:</strong></div>
+  <div class="log"></div>
+</div>
+ +

The {{HTMLElement("div")}} with the class "box" is just a container for layout purposes, presenting the contents with a box around it. The <div> whose class is "log" is the container for the log text itself.

+ +

CSS

+ +

The following CSS styles our example content.

+ +
.box {
+  width: 600px;
+  height: 300px;
+  border: 1px solid black;
+  padding: 2px 4px;
+  overflow-y: scroll;
+  overflow-x: auto;
+}
+
+.log {
+  margin-top: 8px;
+  font-family: monospace;
+}
+ +

Result

+ +

The resulting content looks like this. You can see output into the log by moving the mouse in and out of the box, clicking in it, and so forth.

+ +

{{EmbedLiveSample("Example", 640, 350)}}

+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#dom-element-innerhtml', 'Element.innerHTML')}}{{Spec2('DOM Parsing')}}Initial definition
+ +

Browser compatibility

+ + + +

{{Compat("api.Element.innerHTML")}}

+ +

See also

+ + diff --git a/files/zh-tw/web/api/element/insertadjacenthtml/index.html b/files/zh-tw/web/api/element/insertadjacenthtml/index.html new file mode 100644 index 0000000000..6b9da0f403 --- /dev/null +++ b/files/zh-tw/web/api/element/insertadjacenthtml/index.html @@ -0,0 +1,135 @@ +--- +title: Element.insertAdjacentHTML() +slug: Web/API/Element/insertAdjacentHTML +translation_of: Web/API/Element/insertAdjacentHTML +--- +
{{APIRef("DOM")}}
+ +

insertAdjacentHTML() 把傳入的字串解析成 HTML 或 XML,並把該節點插入到 DOM 樹指定的位置。它不會重新解析被使用的元素,因此他不會破壞該元素裡面原有的元素。這避免了序列化的複雜步驟,使得它比直接操作  innerHTML 快上許多。

+ +

Syntax

+ +
element.insertAdjacentHTML(position, text);
+ +

Parameters

+ +
+
position
+
A {{domxref("DOMString")}} representing the position relative to the element; must be one of the following strings: +
    +
  • 'beforebegin': 在 element 之前。
  • +
  • 'afterbegin': 在 element 裡面,第一個子元素之前。
  • +
  • 'beforeend': 在 element 裡面,最後一個子元素之後。
  • +
  • 'afterend': 在 element 之後。
  • +
+
+
text
+
text 是即將被解析並插入到 DOM 樹裡的字串。
+
+ +

Visualization of position names

+ +
<!-- beforebegin -->
+<p>
+  <!-- afterbegin -->
+  foo
+  <!-- beforeend -->
+</p>
+<!-- afterend -->
+ +
Note:  beforebegin 和 afterend 只在該節點位於 DOM 樹內、並且有母元素時有效。
+ +

Example

+ +
// <div id="one">one</div>
+var d1 = document.getElementById('one');
+d1.insertAdjacentHTML('afterend', '<div id="two">two</div>');
+
+// At this point, the new structure is:
+// <div id="one">one</div><div id="two">two</div>
+ +

Notes

+ +

Security Considerations

+ +

When inserting HTML into a page by using insertAdjacentHTML be careful not to use user input that hasn't been escaped.

+ +

It is not recommended you use insertAdjacentHTML when inserting plain text; instead, use the Node.textContent property or Element.insertAdjacentText() method. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.

+ +

Specification

+ + + + + + + + + + + + + + + + +
SpecificationStatusComment
{{SpecName('DOM Parsing', '#widl-Element-insertAdjacentHTML-void-DOMString-position-DOMString-text', 'Element.insertAdjacentHTML()')}}{{ Spec2('DOM Parsing') }} 
+ +

Browser compatibility

+ +

{{ CompatibilityTable() }}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support1.0{{ CompatGeckoDesktop("8.0") }}4.07.04.0 (527)
+
+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureAndroidFirefox Mobile (Gecko)IE PhoneOpera MobileSafari Mobile
Basic support{{ CompatUnknown() }}{{ CompatGeckoMobile("8.0") }}{{ CompatUnknown() }}{{ CompatUnknown() }}{{ CompatUnknown() }}
+
+ +

See also

+ + diff --git a/files/zh-tw/web/api/element/queryselectorall/index.html b/files/zh-tw/web/api/element/queryselectorall/index.html new file mode 100644 index 0000000000..6f777763bf --- /dev/null +++ b/files/zh-tw/web/api/element/queryselectorall/index.html @@ -0,0 +1,140 @@ +--- +title: Element.querySelectorAll() +slug: Web/API/Element/querySelectorAll +translation_of: Web/API/Element/querySelectorAll +--- +
{{APIRef("DOM")}}
+ +

總覽

+ +

Returns a non-live NodeList of all elements descended from the element on which it is invoked that matches the specified group of CSS selectors. (The base element itself is not included, even if it matches.)

+ +

表達式

+ +
elementList = baseElement.querySelectorAll(selectors);
+ +
+
elementList
+
is a non-live node list [ NodeList[elements] of element objects.
+
baseElement
+
is an element object.
+
selectors
+
is a group of selectors to match on or elements of the DOM. 
+
+ +

範例

+ +

下例是從整個網頁的 body 中,取得所有 p 元素:

+ +
let matches = document.body.querySelectorAll('p');
+
+ +

This example returns a list of p children elements under a container, whose parent is a div that has the class 'highlighted':

+ +
let el = document.querySelector('#test');    //return an element with id='test'
+let matches = el.querySelectorAll('div.highlighted > p'); // return a NodeList of p wrapped in a div with attribute class "highlighted"
+
+ +

下例是取得所有有 attribute data-srciframe 元素:

+ +
let matches = el.querySelectorAll('iframe[data-src]');
+
+ +

+ +

If the specified “selectors” are not found inside the DOM of the page, the method queryselectorAll returns an empty NodeList as specified below:

+ +
> let x = document.body.querySelectorAll('.highlighted'); //case: if the class highlighted doesn't exist in any attribute "class" of the DOM the result is
+> [] //empty NodeList
+ +

querySelectorAll() was introduced in the WebApps API.

+ +

The string argument pass to querySelectorAll must follow the CSS syntax. See {{domxref("document.querySelector")}} for a concrete example.

+ +

We could access a single item inside the NodeList in the following way:

+ +
let x = document.body.querySelectorAll('.highlighted');
+x.length; //return the size of x
+x[i_item]; //where i_item has a value between 0 and x.length-1. The operator "[]" return as in an array the element at index "i_item"
+
+ +

We could iterate inside a NodeList with the construct for(....) {...} as in the following code:

+ +
 let x = document.body.querySelectorAll('.highlighted');
+ let index = 0;
+ for( index=0; index < x.length; index++ ) {
+       console.log(x[index]);
+ }
+ +

So in the above way, it is possible to manage and modify the behaviour of the page.

+ +

Quirks

+ +

querySelectorAll() behaves differently than most common JavaScript DOM libraries, which might lead to unexpected results:

+ +
<div class="outer">
+  <div class="select">
+    <div class="inner">
+    </div>
+  </div>
+</div>
+ +
let select = document.querySelector('.select');
+let inner = select.querySelectorAll('.outer .inner');
+inner.length; // 1, not 0!
+
+ +

In this example, when selecting .outer .inner in the context of .select, .inner is still found, even though .outer is not a descendant of the baseElement (.select).
+ querySelectorAll() only verifies that the last element in the selector is within the baseElement.

+ +

The :scope pseudo-class restores the expected behavior, only matching selectors on descendants of the baseElement:

+ +
let select = document.querySelector('.select');
+let inner = select.querySelectorAll(':scope .outer .inner');
+inner.length; // 0
+
+ +

規範

+ + + + + + + + + + + + + + + + + + + + + + + + + + +
規範狀態評論
{{SpecName('DOM4','#dom-parentnode-queryselectorallselectors','querySelectorAll')}}{{Spec2('DOM4')}} 
{{SpecName('Selectors API Level 2','#queryselectorall','querySelectorAll')}}{{Spec2('Selectors API Level 2')}} 
{{SpecName('Selectors API Level 1','#queryselectorall','querySelectorAll')}}{{Spec2('Selectors API Level 1')}} 
+ +

瀏覽器相容性

+ + + +
{{Compat("api.Element.querySelectorAll")}}
+ +

[1] Supported in Opera 15+ by enabling the "Enable <style scoped>" or "Enable experimental Web Platform features" flag in chrome://flags.

+ +

參見

+ + diff --git a/files/zh-tw/web/api/element/scrollheight/index.html b/files/zh-tw/web/api/element/scrollheight/index.html new file mode 100644 index 0000000000..eabf9987bf --- /dev/null +++ b/files/zh-tw/web/api/element/scrollheight/index.html @@ -0,0 +1,170 @@ +--- +title: Element.scrollHeight +slug: Web/API/Element/scrollHeight +tags: + - API + - Reference +translation_of: Web/API/Element/scrollHeight +--- +

{{APIRef("DOM")}}

+ +

Element.scrollHeight 是衡量元素包含因為 overflow 而沒顯示在螢幕上的內容高度的唯讀屬性. scrollHeight 的值相等於元素要求 clientHeight 在視域中沒有使用滾動條顯示所有內容的最小高度值 . 這當中只包含 padding, 並不包含 margin.

+ +
+

這個屬性會以四捨五入進位取整數. 如果要使用非整數值, 使用 {{ domxref("Element.getBoundingClientRect()") }}.

+
+ +

表達式

+ +
var intElemScrollHeight = document.getElementById(id_attribute_value).scrollHeight;
+
+ +

intElemScrollHeight 是個儲存了元素 scrollHeight 的正整數變數. scrollHeight是唯讀的屬性.

+ +

範例

+ +
+
+

padding-top

+ +

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

+ +

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

+ +

padding-bottom

+
+Left Top Right Bottom margin-top margin-bottom border-top border-bottom
+ +

Image:scrollHeight.png

+ +

問題與解決方法

+ +

了解元素是否被滾輪完全滾過

+ +

下面的等式代表如果元素被完全滾過將會回傳 true ,  否則回傳 false.

+ +
element.scrollHeight - element.scrollTop === element.clientHeight
+ +

scrollHeight 範例

+ +

藉由 onscroll 事件, 這個等式對於決定使用者是否已經讀完文字內容是很有用 (參見 element.scrollTopelement.clientHeight 屬性). 範例:

+ +

HTML

+ +
<form name="registration">
+  <p>
+    <textarea id="rules">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum at laoreet magna.
+Aliquam erat volutpat. Praesent molestie, dolor ut eleifend aliquam, mi ligula ultrices sapien, quis cursus
+neque dui nec risus. Duis tincidunt lobortis purus eu aliquet. Quisque in dignissim magna. Aenean ac lorem at
+velit ultrices consequat. Nulla luctus nisi ut libero cursus ultrices. Pellentesque nec dignissim enim. Phasellus
+ut quam lacus, sed ultricies diam. Vestibulum convallis rutrum dolor, sit amet egestas velit scelerisque id.
+Proin non dignissim nisl. Sed mi odio, ullamcorper eget mattis id, malesuada vitae libero. Integer dolor lorem,
+mattis sed dapibus a, faucibus id metus. Duis iaculis dictum pulvinar. In nisi nibh, dapibus ac blandit at, porta
+at arcu. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Praesent
+dictum ipsum aliquet erat eleifend sit amet sollicitudin felis tempus. Aliquam congue cursus venenatis. Maecenas
+luctus pellentesque placerat. Mauris nisl odio, condimentum sed fringilla a, consectetur id ligula. Praesent sem
+sem, aliquet non faucibus vitae, iaculis nec elit. Nullam volutpat, lectus et blandit bibendum, nulla lorem congue
+turpis, ac pretium tortor sem ut nibh. Donec vel mi in ligula hendrerit sagittis. Donec faucibus viverra fermentum.
+Fusce in arcu arcu. Nullam at dignissim massa. Cras nibh est, pretium sit amet faucibus eget, sollicitudin in
+ligula. Vivamus vitae urna mauris, eget euismod nunc. Aenean semper gravida enim non feugiat. In hac habitasse
+platea dictumst. Cras eleifend nisl volutpat ante condimentum convallis. Donec varius dolor malesuada erat
+consequat congue. Donec eu lacus ut sapien venenatis tincidunt. Quisque sit amet tellus et enim bibendum varius et
+a orci. Donec aliquet volutpat scelerisque. Proin et tortor dolor. Ut aliquet, dolor a mattis sodales, odio diam
+pulvinar sem, egestas pretium magna eros vitae felis. Nam vitae magna lectus, et ornare elit. Morbi feugiat, ipsum
+ac mattis congue, quam neque mollis tortor, nec mollis nisl dolor a tortor. Maecenas varius est sit amet elit
+interdum quis placerat metus posuere. Duis malesuada justo a diam vestibulum vel aliquam nisi ornare. Integer
+laoreet nisi a odio ornare non congue turpis eleifend. Cum sociis natoque penatibus et magnis dis parturient montes,
+nascetur ridiculus mus. Cras vulputate libero sed arcu iaculis nec lobortis orci fermentum.
+    </textarea>
+  </p>
+  <p>
+    <input type="checkbox" name="accept" id="agree" />
+    <label for="agree">I agree</label>
+    <input type="submit" id="nextstep" value="Next" />
+  </p>
+</form>
+ +

CSS

+ +
#notice {
+  display: inline-block;
+  margin-bottom: 12px;
+  border-radius: 5px;
+  width: 600px;
+  padding: 5px;
+  border: 2px #7FDF55 solid;
+}
+
+#rules {
+  width: 600px;
+  height: 130px;
+  padding: 5px;
+  border: #2A9F00 solid 2px;
+  border-radius: 5px;
+}
+ +

JavaScript

+ +
function checkReading () {
+  if (checkReading.read) {
+    return;
+  }
+  checkReading.read = this.scrollHeight - this.scrollTop === this.clientHeight;
+  document.registration.accept.disabled = document.getElementById("nextstep").disabled = !checkReading.read;
+  checkReading.noticeBox.innerHTML = checkReading.read ? "Thank you." : "Please, scroll and read the following text.";
+}
+
+onload = function () {
+  var oToBeRead = document.getElementById("rules");
+  checkReading.noticeBox = document.createElement("span");
+  document.registration.accept.checked = false;
+  checkReading.noticeBox.id = "notice";
+  oToBeRead.parentNode.insertBefore(checkReading.noticeBox, oToBeRead);
+  oToBeRead.parentNode.insertBefore(document.createElement("br"), oToBeRead);
+  oToBeRead.onscroll = checkReading;
+  checkReading.call(oToBeRead);
+}
+ +

{{ EmbedLiveSample('scrollHeight_Demo', '640', '400') }}

+ +

規範

+ +

scrollHeight 是 MSIE's DHTML 物件模型的一部份. scrollHeight 紀錄在下列的規範: {{SpecName("CSSOM View")}}.

+ +

瀏覽器相容性

+ + + + + + + + + + + + + + + + + + + + + + + + +
瀏覽器最低版本
Internet Explorer8.0
Firefox (Gecko)3.0 (1.9)
Opera?
Safari | Chrome | WebKit4.0 | 4.0 | ?
+ +

In FireFox versions earlier than 21: When an element's content does not generate a vertical scrollbar, then its scrollHeight property is equal to its clientHeight property. This can mean either the content is too short to require a scrollbar or that the element has CSS style overflow value of visible (non-scrollable).

+ +

參見

+ + diff --git a/files/zh-tw/web/api/element/scrolltop/index.html b/files/zh-tw/web/api/element/scrolltop/index.html new file mode 100644 index 0000000000..f4fdfe8e09 --- /dev/null +++ b/files/zh-tw/web/api/element/scrolltop/index.html @@ -0,0 +1,73 @@ +--- +title: Element.scrollTop +slug: Web/API/Element/scrollTop +tags: + - API + - CSSOM View + - Reference +translation_of: Web/API/Element/scrollTop +--- +

{{ APIRef("DOM") }}

+ +

Element.scrollTop 屬性可以設置和獲取元素被向上捲動的高度(pixels). 元素的 scrollTop 是元素頂端和能被看見的最頂端之間的距離. 當元素並未產生滾動條, 那麼 scrollTop 的值預設為 0.

+ +

表達式

+ +
// 獲得已經被滾動的距離(pixels)
+var  intElemScrollTop = someElement.scrollTop;
+
+ +

intElemScrollTop 為 {{domxref("element")}}已經被滾動的距離(pixels ).

+ +
// 設置已經被滾動的距離(pixels)
+element.scrollTop = intValue;
+
+ +

scrollTop 可以被設置為任何和正整數, 注意事項:

+ + + +

範例

+ +
+
+

padding-top

+ +

Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

+ +

Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

+ +

padding-bottom

+
+Left Top Right Bottom margin-top margin-bottom border-top border-bottom
+ +

Image:scrollTop.png

+ +

規範

+ + + + + + + + + + + + + + +
規範狀態
{{SpecName('CSSOM View', '#dom-element-scrolltop', 'scrollTop')}}{{Spec2("CSSOM View")}} 
+ +

參閱

+ + diff --git a/files/zh-tw/web/api/element/touchcancel_event/index.html b/files/zh-tw/web/api/element/touchcancel_event/index.html new file mode 100644 index 0000000000..99fa1c27a2 --- /dev/null +++ b/files/zh-tw/web/api/element/touchcancel_event/index.html @@ -0,0 +1,169 @@ +--- +title: touchcancel +slug: Web/API/Element/touchcancel_event +translation_of: Web/API/Element/touchcancel_event +--- +

{{APIRef}}

+ +

touchcancel 觸控點發生失效的事件被觸發(例如太多觸控點時)

+ +

一般資訊

+ +
+
規範
+
Touch Events
+
介面
+
TouchEvent
+
起泡事件
+
+
可取消
+
+
對象
+
Document, Element
+
預設行為
+
+
+ +

屬性

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
PropertyTypeDescription
target {{readonlyInline}}EventTargetThe event target (the topmost target in the DOM tree).
type {{readonlyInline}}DOMStringThe type of event.
bubbles {{readonlyInline}}BooleanWhether the event normally bubbles or not.
cancelable {{readonlyInline}}BooleanWhether the event is cancellable or not.
view {{readonlyInline}}WindowProxydocument.defaultView (window of the document)
detail {{readonlyInline}}long (float)0.
touches {{readonlyInline}}TouchListA list of Touches for every point of contact currently touching the surface.
targetTouches {{readonlyInline}}TouchListA list of Touches for every point of contact that is touching the surface and started on the element that is the target of the current event.
changedTouches {{readonlyInline}}TouchListA list of Touches for every point of contact which contributed to the event.
+ For the touchstart event this must be a list of the touch points that just became active with the current event. For the touchmove event this must be a list of the touch points that have moved since the last event. For the touchend and touchcancel events this must be a list of the touch points that have just been removed from the surface.
ctrlKey {{readonlyInline}}booleantrue if the control key was down when the event was fired. false otherwise.
shiftKey {{readonlyInline}}booleantrue if the shift key was down when the event was fired. false otherwise.
altKey {{readonlyInline}}booleantrue if the alt key was down when the event was fired. false otherwise.
metaKey {{readonlyInline}}booleantrue if the meta key was down when the event was fired. false otherwise.
+ +

範例

+ +

各種觸控事件的範例:Touch events

+ +

瀏覽器相容性

+ +

{{CompatibilityTable}}

+ +
+ + + + + + + + + + + + + + + + + + + +
FeatureChromeFirefox (Gecko)Internet ExplorerOperaSafari (WebKit)
Basic support{{CompatChrome("22.0")}}{{CompatGeckoDesktop("18.0")}}{{CompatNo}}{{CompatNo}}{{CompatNo}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
FeatureAndroidAndroid WebviewChrome for AndroidFirefox Mobile (Gecko)Firefox OSIE MobileOpera MobileSafari Mobile
Basic support{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("6.0")}}{{CompatVersionUnknown}}11{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

相關事件

+ +

{{ domxref("GlobalEventHandlers.ontouchcancel","ontouchcancel")}}

-- cgit v1.2.3-54-g00ecf