From 2d279a6eeea344d0f9ab61adc4d71efb68066f22 Mon Sep 17 00:00:00 2001 From: "Queen Vinyl Da.i'gyu-Kazotetsu" Date: Fri, 28 Jul 2023 22:47:44 -0700 Subject: [PATCH] zh-cn: Format /web/api using Prettier (part 5) (#14679) Co-authored-by: Allo --- files/zh-cn/web/api/file/type/index.md | 2 +- .../web/api/file/webkitrelativepath/index.md | 24 +- .../firefox_support/index.md | 3 +- .../index.md | 32 +- files/zh-cn/web/api/filelist/index.md | 66 ++- .../web/api/filereader/abort_event/index.md | 80 ++-- .../web/api/filereader/filereader/index.md | 2 +- .../web/api/filereader/load_event/index.md | 77 ++-- .../filereader/readasbinarystring/index.md | 14 +- .../web/api/filereader/readasdataurl/index.md | 52 ++- .../web/api/filereader/readystate/index.md | 6 +- .../readentries/index.md | 2 +- .../web/api/filesystemfileentry/index.md | 46 +- files/zh-cn/web/api/formdata/append/index.md | 8 +- files/zh-cn/web/api/formdata/delete/index.md | 2 +- files/zh-cn/web/api/formdata/entries/index.md | 8 +- .../zh-cn/web/api/formdata/formdata/index.md | 16 +- files/zh-cn/web/api/formdata/get/index.md | 6 +- files/zh-cn/web/api/formdata/getall/index.md | 6 +- files/zh-cn/web/api/formdata/has/index.md | 6 +- files/zh-cn/web/api/formdata/keys/index.md | 6 +- files/zh-cn/web/api/formdata/set/index.md | 4 +- .../formdata/using_formdata_objects/index.md | 58 ++- files/zh-cn/web/api/formdata/values/index.md | 6 +- .../web/api/fullscreen_api/guide/index.md | 30 +- files/zh-cn/web/api/fullscreen_api/index.md | 16 +- files/zh-cn/web/api/gamepad/index.md | 12 +- .../using_the_gamepad_api/index.md | 99 +++-- files/zh-cn/web/api/gamepadbutton/index.md | 24 +- .../web/api/gamepadbutton/pressed/index.md | 2 +- .../web/api/gamepadbutton/value/index.md | 2 +- .../web/api/gamepadevent/gamepad/index.md | 12 +- files/zh-cn/web/api/gamepadevent/index.md | 17 +- .../web/api/geolocation/clearwatch/index.md | 14 +- .../geolocation/getcurrentposition/index.md | 16 +- .../api/geolocation/watchposition/index.md | 10 +- .../using_the_geolocation_api/index.md | 42 +- .../web/api/geolocationpositionerror/index.md | 8 +- files/zh-cn/web/api/hashchangeevent/index.md | 26 +- .../web/api/hashchangeevent/newurl/index.md | 4 +- .../web/api/hashchangeevent/oldurl/index.md | 4 +- files/zh-cn/web/api/headers/append/index.md | 14 +- files/zh-cn/web/api/headers/delete/index.md | 8 +- files/zh-cn/web/api/headers/entries/index.md | 6 +- files/zh-cn/web/api/headers/get/index.md | 10 +- files/zh-cn/web/api/headers/has/index.md | 6 +- files/zh-cn/web/api/headers/headers/index.md | 12 +- files/zh-cn/web/api/headers/index.md | 4 +- files/zh-cn/web/api/headers/keys/index.md | 8 +- files/zh-cn/web/api/headers/set/index.md | 10 +- files/zh-cn/web/api/headers/values/index.md | 6 +- files/zh-cn/web/api/history/back/index.md | 12 +- files/zh-cn/web/api/history/forward/index.md | 10 +- files/zh-cn/web/api/history/go/index.md | 4 +- .../api/history/scrollrestoration/index.md | 10 +- files/zh-cn/web/api/history/state/index.md | 2 +- .../web/api/history_api/example/index.md | 417 ++++++++++-------- files/zh-cn/web/api/history_api/index.md | 22 +- files/zh-cn/web/api/html_dom_api/index.md | 10 +- .../api/html_dom_api/microtask_guide/index.md | 21 +- .../drag_operations/index.md | 21 +- .../file_drag_and_drop/index.md | 19 +- .../web/api/html_drag_and_drop_api/index.md | 91 ++-- .../recommended_drag_types/index.md | 109 +++-- .../web/api/htmlaudioelement/audio/index.md | 2 +- files/zh-cn/web/api/htmlaudioelement/index.md | 8 +- .../zh-cn/web/api/htmlbuttonelement/index.md | 6 +- .../htmlcanvaselement/capturestream/index.md | 2 +- .../api/htmlcanvaselement/getcontext/index.md | 4 +- .../web/api/htmlcanvaselement/height/index.md | 2 +- .../api/htmlcanvaselement/mozopaque/index.md | 2 +- .../web/api/htmlcanvaselement/toblob/index.md | 71 +-- .../api/htmlcanvaselement/todataurl/index.md | 17 +- .../transfercontroltooffscreen/index.md | 4 +- .../webglcontextlost_event/index.md | 10 +- .../web/api/htmlcanvaselement/width/index.md | 2 +- files/zh-cn/web/api/htmlcollection/index.md | 2 + .../web/api/htmlcollection/item/index.md | 6 +- .../web/api/htmlcollection/nameditem/index.md | 12 +- .../htmldetailselement/toggle_event/index.md | 27 +- .../zh-cn/web/api/htmldialogelement/index.md | 68 +-- .../web/api/htmldialogelement/show/index.md | 93 ++-- .../api/htmlelement/accesskeylabel/index.md | 10 +- .../htmlelement/beforeinput_event/index.md | 10 +- .../web/api/htmlelement/change_event/index.md | 16 +- .../zh-cn/web/api/htmlelement/click/index.md | 12 +- .../web/api/htmlelement/dataset/index.md | 8 +- .../web/api/htmlelement/drag_event/index.md | 22 +- .../api/htmlelement/dragend_event/index.md | 10 +- .../api/htmlelement/dragenter_event/index.md | 6 +- .../api/htmlelement/dragleave_event/index.md | 8 +- .../api/htmlelement/dragover_event/index.md | 4 +- .../api/htmlelement/dragstart_event/index.md | 4 +- .../web/api/htmlelement/drop_event/index.md | 8 +- .../web/api/htmlelement/error_event/index.md | 21 +- .../zh-cn/web/api/htmlelement/hidden/index.md | 32 +- files/zh-cn/web/api/htmlelement/index.md | 66 +-- .../web/api/htmlelement/input_event/index.md | 18 +- .../zh-cn/web/api/htmlelement/style/index.md | 2 +- .../web/api/htmlfieldsetelement/index.md | 24 +- 100 files changed, 1262 insertions(+), 1059 deletions(-) diff --git a/files/zh-cn/web/api/file/type/index.md b/files/zh-cn/web/api/file/type/index.md index 91529286b6e1dd..dfc32aa7c5c212 100644 --- a/files/zh-cn/web/api/file/type/index.md +++ b/files/zh-cn/web/api/file/type/index.md @@ -20,7 +20,7 @@ var name = file.type; ## 示例 ```html - + ``` ```js diff --git a/files/zh-cn/web/api/file/webkitrelativepath/index.md b/files/zh-cn/web/api/file/webkitrelativepath/index.md index fcfdec5b6a493c..6aa908ecd9d1bf 100644 --- a/files/zh-cn/web/api/file/webkitrelativepath/index.md +++ b/files/zh-cn/web/api/file/webkitrelativepath/index.md @@ -31,16 +31,20 @@ slug: Web/API/File/webkitRelativePath ### JavaScript ```js -document.getElementById("filepicker").addEventListener("change", function(event) { - let output = document.getElementById("listing"); - let files = event.target.files; - - for (let i=0; i + @@ -104,7 +104,7 @@ const numFiles = files.length; ]; const exponent = Math.min( Math.floor(Math.log(numberOfBytes) / Math.log(1024)), - units.length - 1 + units.length - 1, ); const approx = numberOfBytes / 1024 ** exponent; const output = @@ -117,7 +117,7 @@ const numFiles = files.length; uploadInput.files.length; document.getElementById("fileSize").textContent = output; }, - false + false, ); @@ -153,7 +153,7 @@ fileSelect.addEventListener( fileElem.click(); } }, - false + false, ); ``` @@ -308,7 +308,7 @@ URL.revokeObjectURL(objectURL); ``` -这就建立了我们的文件 {{HTMLElement("input")}} 元素,以及调用文件选取器的链接(因为我们把文件 input 隐藏起来,以防止显示那个不那么吸引人的用户界面)。这在[使用 click() 方法隐藏文件 input 元素](#通过_click()_方法使用隐藏的_file_input_元素)一节中有所说明,调用文件选取器的方法也是如此。 +这就建立了我们的文件 {{HTMLElement("input")}} 元素,以及调用文件选取器的链接(因为我们把文件 input 隐藏起来,以防止显示那个不那么吸引人的用户界面)。这在[使用 click() 方法隐藏文件 input 元素](<#通过_click()_方法使用隐藏的_file_input_元素>)一节中有所说明,调用文件选取器的方法也是如此。 `handleFiles()` 方法如下: @@ -325,7 +325,7 @@ fileSelect.addEventListener( } e.preventDefault(); // 避免导航至“#” }, - false + false, ); fileElem.addEventListener("change", handleFiles, false); @@ -364,12 +364,12 @@ function handleFiles() { 2. 通过调用列表的 {{DOMxRef("Node.appendChild()")}} 方法来将新的列表元素插入到 {{HTMLElement("div")}} 块。 3. 遍历 `files` 代表的文件集合 {{DOMxRef("FileList")}} 中的每个 {{DOMxRef("File")}}: - 1. 创建一个新的列表项({{HTMLElement("li")}})元素并插入到列表中。 - 2. 创建一个新的图片({{HTMLElement("img")}})元素。 - 3. 设置图片的源为一个新的指代文件的对象 URL,使用 {{DOMxRef("URL.createObjectURL()")}} 来创建 blob URL。 - 4. 设置图片的高度为 60 像素。 - 5. 设置图片的 load 事件处理器来释放对象 URL,当图片加载完成之后对象 URL 就不再需要了。这个可以通过调用 {{DOMxRef("URL.revokeObjectURL()")}} 方法并且传递 `img.src`中的对象 URL 字符串来实现。 - 6. 将新的列表项添加到列表中。 + 1. 创建一个新的列表项({{HTMLElement("li")}})元素并插入到列表中。 + 2. 创建一个新的图片({{HTMLElement("img")}})元素。 + 3. 设置图片的源为一个新的指代文件的对象 URL,使用 {{DOMxRef("URL.createObjectURL()")}} 来创建 blob URL。 + 4. 设置图片的高度为 60 像素。 + 5. 设置图片的 load 事件处理器来释放对象 URL,当图片加载完成之后对象 URL 就不再需要了。这个可以通过调用 {{DOMxRef("URL.revokeObjectURL()")}} 方法并且传递 `img.src`中的对象 URL 字符串来实现。 + 6. 将新的列表项添加到列表中。 这是上面代码的一个在线示例: @@ -415,7 +415,7 @@ function FileUpload(img, file) { self.ctrl.update(percentage); } }, - false + false, ); xhr.upload.addEventListener( @@ -425,11 +425,11 @@ function FileUpload(img, file) { const canvas = self.ctrl.ctx.canvas; canvas.parentNode.removeChild(canvas); }, - false + false, ); xhr.open( "POST", - "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php" + "http://demos.hacks.mozilla.org/paul/demos/resources/webservices/devnull.php", ); xhr.overrideMimeType("text/plain; charset=x-user-defined-binary"); reader.onload = (evt) => { @@ -453,7 +453,7 @@ function createThrobber(img) { 0, 0, (throbberWidth * percent) / 100, - throbberHeight + throbberHeight, ); if (percent === 100) { throbber.ctx.fillStyle = "green"; diff --git a/files/zh-cn/web/api/filelist/index.md b/files/zh-cn/web/api/filelist/index.md index 9ed0b6f80ff061..430941fb80c1ae 100644 --- a/files/zh-cn/web/api/filelist/index.md +++ b/files/zh-cn/web/api/filelist/index.md @@ -20,7 +20,7 @@ slug: Web/API/FileList 下面的一行代码演示如何获取到一个 FileList 对象中的第一个文件 ([`File`](/zh-CN/docs/Web/API/File) 对象): ```js -var file = document.getElementById('fileItem').files[0]; +var file = document.getElementById("fileItem").files[0]; ``` ## 方法概述 @@ -70,53 +70,47 @@ var file; // 遍历所有文件 for (var i = 0; i < files.length; i++) { - - // 取得一个文件 - file = files.item(i); - // 这样也行 - file = files[i]; - // 取得文件名 - alert(file.name); + // 取得一个文件 + file = files.item(i); + // 这样也行 + file = files[i]; + // 取得文件名 + alert(file.name); } ``` 下面是一个更完整的例子。 ```html - + - - - - - - - - - - + } + }; + // 设置 change 事件处理函数 + document.querySelector("#myfiles").onchange = pullfiles; + ``` diff --git a/files/zh-cn/web/api/filereader/abort_event/index.md b/files/zh-cn/web/api/filereader/abort_event/index.md index c319d0952853be..65687bf4a53f35 100644 --- a/files/zh-cn/web/api/filereader/abort_event/index.md +++ b/files/zh-cn/web/api/filereader/abort_event/index.md @@ -1,5 +1,5 @@ --- -title: 'FileReader: 中止事件 (abort)' +title: "FileReader: 中止事件 (abort)" slug: Web/API/FileReader/abort_event --- @@ -36,22 +36,22 @@ slug: Web/API/FileReader/abort_event ```html
+
+ + +
-
- - -
- - 图像预览... - -
- - -
+ 图像预览... +
+ +
+
``` ```css hidden @@ -63,15 +63,15 @@ img.preview { width: 18rem; height: 5rem; border: 1px solid black; - margin: .2rem; - padding: .2rem; + margin: 0.2rem; + padding: 0.2rem; } .example { display: grid; grid-template-areas: - "select log" - "preview log"; + "select log" + "preview log"; } .file-select { @@ -86,7 +86,7 @@ img.preview { grid-area: log; } -.event-log>label { +.event-log > label { display: block; } @@ -99,38 +99,40 @@ img.preview { ```js const fileInput = document.querySelector('input[type="file"]'); -const preview = document.querySelector('img.preview'); -const eventLog = document.querySelector('.event-log-contents'); +const preview = document.querySelector("img.preview"); +const eventLog = document.querySelector(".event-log-contents"); const reader = new FileReader(); function handleEvent(event) { - eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; + eventLog.textContent = + eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; - if (event.type === "load") { - preview.src = reader.result; - } + if (event.type === "load") { + preview.src = reader.result; + } } function addListeners(reader) { - reader.addEventListener('loadstart', handleEvent); - reader.addEventListener('load', handleEvent); - reader.addEventListener('loadend', handleEvent); - reader.addEventListener('progress', handleEvent); - reader.addEventListener('error', handleEvent); - reader.addEventListener('abort', handleEvent); + reader.addEventListener("loadstart", handleEvent); + reader.addEventListener("load", handleEvent); + reader.addEventListener("loadend", handleEvent); + reader.addEventListener("progress", handleEvent); + reader.addEventListener("error", handleEvent); + reader.addEventListener("abort", handleEvent); } function handleSelected(e) { - eventLog.textContent = ''; - const selectedFile = fileInput.files[0]; - if (selectedFile) { - addListeners(reader); - reader.readAsDataURL(selectedFile); - } - reader.abort(); + eventLog.textContent = ""; + const selectedFile = fileInput.files[0]; + if (selectedFile) { + addListeners(reader); + reader.readAsDataURL(selectedFile); + } + reader.abort(); } -fileInput.addEventListener('change', handleSelected);返回返回发的 +fileInput.addEventListener("change", handleSelected); +返回返回发的; ``` #### 结果 diff --git a/files/zh-cn/web/api/filereader/filereader/index.md b/files/zh-cn/web/api/filereader/filereader/index.md index 036026435a059e..b4270166463bf2 100644 --- a/files/zh-cn/web/api/filereader/filereader/index.md +++ b/files/zh-cn/web/api/filereader/filereader/index.md @@ -24,7 +24,7 @@ None. ```js function printFile(file) { var reader = new FileReader(); - reader.onload = function(evt) { + reader.onload = function (evt) { console.log(evt.target.result); }; reader.readAsText(file); diff --git a/files/zh-cn/web/api/filereader/load_event/index.md b/files/zh-cn/web/api/filereader/load_event/index.md index 16f7277074f05f..0f3c90f1ea57fd 100644 --- a/files/zh-cn/web/api/filereader/load_event/index.md +++ b/files/zh-cn/web/api/filereader/load_event/index.md @@ -1,5 +1,5 @@ --- -title: 'FileReader: load event' +title: "FileReader: load event" slug: Web/API/FileReader/load_event --- @@ -36,22 +36,22 @@ slug: Web/API/FileReader/load_event ```html
+
+ + +
-
- - -
- - Image preview... - -
- - -
+ Image preview... +
+ +
+
``` ```css hidden @@ -63,15 +63,15 @@ img.preview { width: 18rem; height: 5rem; border: 1px solid black; - margin: .2rem; - padding: .2rem; + margin: 0.2rem; + padding: 0.2rem; } .example { display: grid; grid-template-areas: - "select log" - "preview log"; + "select log" + "preview log"; } .file-select { @@ -86,7 +86,7 @@ img.preview { grid-area: log; } -.event-log>label { +.event-log > label { display: block; } @@ -99,37 +99,38 @@ img.preview { ```js const fileInput = document.querySelector('input[type="file"]'); -const preview = document.querySelector('img.preview'); -const eventLog = document.querySelector('.event-log-contents'); +const preview = document.querySelector("img.preview"); +const eventLog = document.querySelector(".event-log-contents"); const reader = new FileReader(); function handleEvent(event) { - eventLog.textContent = eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; + eventLog.textContent = + eventLog.textContent + `${event.type}: ${event.loaded} bytes transferred\n`; - if (event.type === "load") { - preview.src = reader.result; - } + if (event.type === "load") { + preview.src = reader.result; + } } function addListeners(reader) { - reader.addEventListener('loadstart', handleEvent); - reader.addEventListener('load', handleEvent); - reader.addEventListener('loadend', handleEvent); - reader.addEventListener('progress', handleEvent); - reader.addEventListener('error', handleEvent); - reader.addEventListener('abort', handleEvent); + reader.addEventListener("loadstart", handleEvent); + reader.addEventListener("load", handleEvent); + reader.addEventListener("loadend", handleEvent); + reader.addEventListener("progress", handleEvent); + reader.addEventListener("error", handleEvent); + reader.addEventListener("abort", handleEvent); } function handleSelected(e) { - eventLog.textContent = ''; - const selectedFile = fileInput.files[0]; - if (selectedFile) { - addListeners(reader); - reader.readAsDataURL(selectedFile); - } + eventLog.textContent = ""; + const selectedFile = fileInput.files[0]; + if (selectedFile) { + addListeners(reader); + reader.readAsDataURL(selectedFile); + } } -fileInput.addEventListener('change', handleSelected); +fileInput.addEventListener("change", handleSelected); ``` #### 结果 diff --git a/files/zh-cn/web/api/filereader/readasbinarystring/index.md b/files/zh-cn/web/api/filereader/readasbinarystring/index.md index b068508397ea73..863571f8176a29 100644 --- a/files/zh-cn/web/api/filereader/readasbinarystring/index.md +++ b/files/zh-cn/web/api/filereader/readasbinarystring/index.md @@ -23,18 +23,18 @@ instanceOfFileReader.readAsBinaryString(blob); ## 示例 ```js -var canvas = document.createElement('canvas'); +var canvas = document.createElement("canvas"); var height = 200; -var width = 200; +var width = 200; -canvas.width = width; +canvas.width = width; canvas.height = height; -var ctx = canvas.getContext('2d'); +var ctx = canvas.getContext("2d"); -ctx.strokeStyle = '#090'; +ctx.strokeStyle = "#090"; ctx.beginPath(); -ctx.arc(width/2, height/2, width/2 - width/10, 0, Math.PI*2); +ctx.arc(width / 2, height / 2, width / 2 - width / 10, 0, Math.PI * 2); ctx.stroke(); canvas.toBlob(function (blob) { @@ -42,7 +42,7 @@ canvas.toBlob(function (blob) { reader.onloadend = function () { console.log(reader.result); - } + }; reader.readAsBinaryString(blob); }); diff --git a/files/zh-cn/web/api/filereader/readasdataurl/index.md b/files/zh-cn/web/api/filereader/readasdataurl/index.md index 5d05856a194fbc..d62f95737679d2 100644 --- a/files/zh-cn/web/api/filereader/readasdataurl/index.md +++ b/files/zh-cn/web/api/filereader/readasdataurl/index.md @@ -23,21 +23,25 @@ readAsDataURL(blob) ### HTML ```html -
-Image preview... +
+Image preview... ``` ### JavaScript ```js function previewFile() { - var preview = document.querySelector('img'); - var file = document.querySelector('input[type=file]').files[0]; - var reader = new FileReader(); - - reader.addEventListener("load", function () { - preview.src = reader.result; - }, false); + var preview = document.querySelector("img"); + var file = document.querySelector("input[type=file]").files[0]; + var reader = new FileReader(); + + reader.addEventListener( + "load", + function () { + preview.src = reader.result; + }, + false, + ); if (file) { reader.readAsDataURL(file); @@ -54,7 +58,7 @@ function previewFile() { ### HTML ```html - +
``` @@ -62,33 +66,33 @@ function previewFile() { ```js function previewFiles() { - - var preview = document.querySelector('#preview'); - var files = document.querySelector('input[type=file]').files; + var preview = document.querySelector("#preview"); + var files = document.querySelector("input[type=file]").files; function readAndPreview(file) { - // 确保 `file.name` 符合我们要求的扩展名 - if ( /\.(jpe?g|png|gif)$/i.test(file.name) ) { + if (/\.(jpe?g|png|gif)$/i.test(file.name)) { var reader = new FileReader(); - reader.addEventListener("load", function () { - var image = new Image(); - image.height = 100; - image.title = file.name; - image.src = this.result; - preview.appendChild( image ); - }, false); + reader.addEventListener( + "load", + function () { + var image = new Image(); + image.height = 100; + image.title = file.name; + image.src = this.result; + preview.appendChild(image); + }, + false, + ); reader.readAsDataURL(file); } - } if (files) { [].forEach.call(files, readAndPreview); } - } ``` diff --git a/files/zh-cn/web/api/filereader/readystate/index.md b/files/zh-cn/web/api/filereader/readystate/index.md index 63e6f156640a1c..f74266613b55bd 100644 --- a/files/zh-cn/web/api/filereader/readystate/index.md +++ b/files/zh-cn/web/api/filereader/readystate/index.md @@ -24,13 +24,13 @@ slug: Web/API/FileReader/readyState ```js const reader = new FileReader(); -console.log('EMPTY', reader.readyState); // readyState will be 0 +console.log("EMPTY", reader.readyState); // readyState will be 0 reader.readAsText(blob); -console.log('LOADING', reader.readyState); // readyState will be 1 +console.log("LOADING", reader.readyState); // readyState will be 1 reader.onloadend = () => { - console.log('DONE', reader.readyState); // readyState will be 2 + console.log("DONE", reader.readyState); // readyState will be 2 }; ``` diff --git a/files/zh-cn/web/api/filesystemdirectoryreader/readentries/index.md b/files/zh-cn/web/api/filesystemdirectoryreader/readentries/index.md index 32fbd8e512dbec..b7327a71ab5836 100644 --- a/files/zh-cn/web/api/filesystemdirectoryreader/readentries/index.md +++ b/files/zh-cn/web/api/filesystemdirectoryreader/readentries/index.md @@ -11,7 +11,7 @@ slug: Web/API/FileSystemDirectoryReader/readEntries ## 语法 -```js +```js-nolint readEntries(successCallback) readEntries(successCallback, errorCallback) ``` diff --git a/files/zh-cn/web/api/filesystemfileentry/index.md b/files/zh-cn/web/api/filesystemfileentry/index.md index 7ca7ed098dd475..52c7d1655ac86d 100644 --- a/files/zh-cn/web/api/filesystemfileentry/index.md +++ b/files/zh-cn/web/api/filesystemfileentry/index.md @@ -33,30 +33,32 @@ slug: Web/API/FileSystemFileEntry ```js function onInitFs(fs) { - fs.root.getFile('log.txt', {create: true}, function(fileEntry) { - - // Create a FileWriter object for our FileSystemFileEntry (log.txt). - fileEntry.createWriter(function(fileWriter) { - fileWriter.onwriteend = function(e) { - console.log('Write completed.'); - }; - - fileWriter.onerror = function(e) { - console.log('Write failed: ' + e.toString()); - }; - - // Create a new Blob and write it to log.txt. - var bb = new BlobBuilder(); - bb.append('Meow'); - - fileWriter.write(bb.getBlob('text/plain')); - }, errorHandler); - - }, errorHandler); - + fs.root.getFile( + "log.txt", + { create: true }, + function (fileEntry) { + // Create a FileWriter object for our FileSystemFileEntry (log.txt). + fileEntry.createWriter(function (fileWriter) { + fileWriter.onwriteend = function (e) { + console.log("Write completed."); + }; + + fileWriter.onerror = function (e) { + console.log("Write failed: " + e.toString()); + }; + + // Create a new Blob and write it to log.txt. + var bb = new BlobBuilder(); + bb.append("Meow"); + + fileWriter.write(bb.getBlob("text/plain")); + }, errorHandler); + }, + errorHandler, + ); } -window.requestFileSystem(window.TEMPORARY, 1024*1024, onInitFs, errorHandler); +window.requestFileSystem(window.TEMPORARY, 1024 * 1024, onInitFs, errorHandler); ``` ## 规范 diff --git a/files/zh-cn/web/api/formdata/append/index.md b/files/zh-cn/web/api/formdata/append/index.md index 525ca7108c9d63..cd77f5ab9bff9d 100644 --- a/files/zh-cn/web/api/formdata/append/index.md +++ b/files/zh-cn/web/api/formdata/append/index.md @@ -46,15 +46,15 @@ var formData = new FormData(); // Currently empty 你可以通过 {{domxref("FormData.append")}} 往对象里加入键值对: ```js -formData.append('username', 'Chris'); -formData.append('userpic', myFileInput.files[0], 'chris.jpg'); +formData.append("username", "Chris"); +formData.append("userpic", myFileInput.files[0], "chris.jpg"); ``` 跟常规`表单数据一样,你可以使用同一个名称添加多个值` 。例如 (为了与 PHP 命名习惯一致在名称中添加了 \[]): ```js -formData.append('userpic[]', myFileInput1.files[0], 'chris1.jpg'); -formData.append('userpic[]', myFileInput2.files[0], 'chris2.jpg'); +formData.append("userpic[]", myFileInput1.files[0], "chris1.jpg"); +formData.append("userpic[]", myFileInput2.files[0], "chris2.jpg"); ``` 这项技术使得多文件上传的处理更加简单,因为所得数据结构更有利于循环。 diff --git a/files/zh-cn/web/api/formdata/delete/index.md b/files/zh-cn/web/api/formdata/delete/index.md index 86b19834f5c267..cb2800a44e2632 100644 --- a/files/zh-cn/web/api/formdata/delete/index.md +++ b/files/zh-cn/web/api/formdata/delete/index.md @@ -35,7 +35,7 @@ var formData = new FormData(myForm); 你可以通过 `delete()` 方法来删除键值对: ```js -formData.delete('username'); +formData.delete("username"); ``` ## 规范 diff --git a/files/zh-cn/web/api/formdata/entries/index.md b/files/zh-cn/web/api/formdata/entries/index.md index d0f39715694328..7d478a4d3bed9d 100644 --- a/files/zh-cn/web/api/formdata/entries/index.md +++ b/files/zh-cn/web/api/formdata/entries/index.md @@ -24,12 +24,12 @@ formData.entries(); ```js // Create a test FormData object var formData = new FormData(); -formData.append('key1', 'value1'); -formData.append('key2', 'value2'); +formData.append("key1", "value1"); +formData.append("key2", "value2"); // Display the key/value pairs -for(var pair of formData.entries()) { - console.log(pair[0]+ ', '+ pair[1]); +for (var pair of formData.entries()) { + console.log(pair[0] + ", " + pair[1]); } ``` diff --git a/files/zh-cn/web/api/formdata/formdata/index.md b/files/zh-cn/web/api/formdata/formdata/index.md index 4b562f64e6c461..656d5a9adf69a2 100644 --- a/files/zh-cn/web/api/formdata/formdata/index.md +++ b/files/zh-cn/web/api/formdata/formdata/index.md @@ -11,8 +11,8 @@ slug: Web/API/FormData/FormData ## 语法 -```js -var formData = new FormData(form) +```js-nolint +new FormData(form) ``` ### 参数 @@ -31,7 +31,7 @@ var formData = new FormData(); // 当前为空 你可以使用{{domxref("FormData.append")}}来添加键/值对到表单里面; ```js -formData.append('username', 'Chris'); +formData.append("username", "Chris"); ``` 或者你可以使用可选的 `form` 参数来创建一个带预置数据的 FormData 对象: @@ -40,24 +40,24 @@ formData.append('username', 'Chris');
- +
- +
- +
- +
``` > **备注:** 所有的输入元素都需要有 **name** 属性,否则无法访问到值。 ```js -var myForm = document.getElementById('myForm'); +var myForm = document.getElementById("myForm"); formData = new FormData(myForm); ``` diff --git a/files/zh-cn/web/api/formdata/get/index.md b/files/zh-cn/web/api/formdata/get/index.md index 44c2848d86d9f2..0dae07bc5ef160 100644 --- a/files/zh-cn/web/api/formdata/get/index.md +++ b/files/zh-cn/web/api/formdata/get/index.md @@ -35,14 +35,14 @@ var formData = new FormData(); 使用{{domxref("FormData.append")}}方法添加两个数据: ```js -formData.append('username', 'Chris'); -formData.append('username', 'Bob'); +formData.append("username", "Chris"); +formData.append("username", "Bob"); ``` 接下来使用 `get()` 来返回第一个和 `"username"` 关联的值: ```js -formData.get('username'); // Returns "Chris" +formData.get("username"); // Returns "Chris" ``` ## 规范 diff --git a/files/zh-cn/web/api/formdata/getall/index.md b/files/zh-cn/web/api/formdata/getall/index.md index 245e36f0f753ac..2155fdae1231b8 100644 --- a/files/zh-cn/web/api/formdata/getall/index.md +++ b/files/zh-cn/web/api/formdata/getall/index.md @@ -35,14 +35,14 @@ var formData = new FormData(); 使用 {{domxref("FormData.append")}} 添加两个 `username 的值:` ```js -formData.append('username', 'Chris'); -formData.append('username', 'Bob'); +formData.append("username", "Chris"); +formData.append("username", "Bob"); ``` 下列 `getAll()` 方法会返回一个数组,包含了所有 `username` 的值: ```js -formData.getAll('username'); // Returns ["Chris", "Bob"] +formData.getAll("username"); // Returns ["Chris", "Bob"] ``` ## 规范 diff --git a/files/zh-cn/web/api/formdata/has/index.md b/files/zh-cn/web/api/formdata/has/index.md index c1451780b5a203..9f86945ced5713 100644 --- a/files/zh-cn/web/api/formdata/has/index.md +++ b/files/zh-cn/web/api/formdata/has/index.md @@ -35,9 +35,9 @@ var formData = new FormData(); 下列代码用来检测 `FormData` 对象是否存在 `username` 这个 key。默认检测一次,使用 {{domxref("FormData.append")}} 插入`username` 之后再检测一次: ```js -formData.has('username'); // Returns false -formData.append('username', 'Chris'); -formData.has('username'); // Returns true +formData.has("username"); // Returns false +formData.append("username", "Chris"); +formData.has("username"); // Returns true ``` ## 规范 diff --git a/files/zh-cn/web/api/formdata/keys/index.md b/files/zh-cn/web/api/formdata/keys/index.md index 3d719c80f7bb47..ad8b8e704b58a0 100644 --- a/files/zh-cn/web/api/formdata/keys/index.md +++ b/files/zh-cn/web/api/formdata/keys/index.md @@ -24,12 +24,12 @@ formData.keys(); ```js // 先创建一个 FormData 对象 var formData = new FormData(); -formData.append('key1', 'value1'); -formData.append('key2', 'value2'); +formData.append("key1", "value1"); +formData.append("key2", "value2"); // 输出所有的 key for (var key of formData.keys()) { - console.log(key); + console.log(key); } ``` diff --git a/files/zh-cn/web/api/formdata/set/index.md b/files/zh-cn/web/api/formdata/set/index.md index f75f25c14bb127..8d4875b48e6d35 100644 --- a/files/zh-cn/web/api/formdata/set/index.md +++ b/files/zh-cn/web/api/formdata/set/index.md @@ -43,8 +43,8 @@ var formData = new FormData(); // Currently empty 使用 {{domxref("FormData.set")}} 设置键/值: ```js -formData.set('username', 'Chris'); -formData.set('userpic', myFileInput.files[0], 'chris.jpg'); +formData.set("username", "Chris"); +formData.set("userpic", myFileInput.files[0], "chris.jpg"); ``` ## 规范 diff --git a/files/zh-cn/web/api/formdata/using_formdata_objects/index.md b/files/zh-cn/web/api/formdata/using_formdata_objects/index.md index 7734df23400f49..c7b5e97067ce14 100644 --- a/files/zh-cn/web/api/formdata/using_formdata_objects/index.md +++ b/files/zh-cn/web/api/formdata/using_formdata_objects/index.md @@ -20,7 +20,7 @@ formData.append("userfile", fileInputElement.files[0]); // JavaScript file-like 对象 var content = 'hey!'; // 新文件的正文 -var blob = new Blob([content], { type: "text/xml"}); +var blob = new Blob([content], { type: "text/xml" }); formData.append("webmasterfile", blob); @@ -72,7 +72,15 @@ request.send(formData); ```html
-
+

@@ -86,26 +94,32 @@ request.send(formData); ```js var form = document.forms.namedItem("fileinfo"); -form.addEventListener('submit', function(ev) { - - var oOutput = document.querySelector("div"), +form.addEventListener( + "submit", + function (ev) { + var oOutput = document.querySelector("div"), oData = new FormData(form); - oData.append("CustomField", "This is some extra data"); - - var oReq = new XMLHttpRequest(); - oReq.open("POST", "stash.php", true); - oReq.onload = function(oEvent) { - if (oReq.status == 200) { - oOutput.innerHTML = "Uploaded!"; - } else { - oOutput.innerHTML = "Error " + oReq.status + " occurred when trying to upload your file.
"; - } - }; - - oReq.send(oData); - ev.preventDefault(); -}, false); + oData.append("CustomField", "This is some extra data"); + + var oReq = new XMLHttpRequest(); + oReq.open("POST", "stash.php", true); + oReq.onload = function (oEvent) { + if (oReq.status == 200) { + oOutput.innerHTML = "Uploaded!"; + } else { + oOutput.innerHTML = + "Error " + + oReq.status + + " occurred when trying to upload your file.
"; + } + }; + + oReq.send(oData); + ev.preventDefault(); + }, + false, +); ``` > **备注:** 如果 FormData 对象是通过表单创建的,则表单中指定的请求方式会被应用到方法 open() 中。 @@ -127,8 +141,8 @@ $.ajax({ url: "stash.php", type: "POST", data: fd, - processData: false, // 不处理数据 - contentType: false // 不设置内容类型 + processData: false, // 不处理数据 + contentType: false, // 不设置内容类型 }); ``` diff --git a/files/zh-cn/web/api/formdata/values/index.md b/files/zh-cn/web/api/formdata/values/index.md index 8bc5d233fd36a0..a59b939ebfe5db 100644 --- a/files/zh-cn/web/api/formdata/values/index.md +++ b/files/zh-cn/web/api/formdata/values/index.md @@ -24,12 +24,12 @@ formData.values(); ```js //创建一个 FormData 测试对象 var formData = new FormData(); -formData.append('key1', 'value1'); -formData.append('key2', 'value2'); +formData.append("key1", "value1"); +formData.append("key2", "value2"); //显示值 for (var value of formData.values()) { - console.log(value); + console.log(value); } ``` diff --git a/files/zh-cn/web/api/fullscreen_api/guide/index.md b/files/zh-cn/web/api/fullscreen_api/guide/index.md index 9b40e3fe8c9731..7ec1d46ab86a3a 100644 --- a/files/zh-cn/web/api/fullscreen_api/guide/index.md +++ b/files/zh-cn/web/api/fullscreen_api/guide/index.md @@ -84,11 +84,15 @@ if (elem.requestFullscreen) { 当页面加载完成时,这段代码可以设置一个事件监听器以监听 Enter 键。 ```js -document.addEventListener("keydown", function(e) { - if (e.keyCode == 13) { - toggleFullScreen(); - } -}, false); +document.addEventListener( + "keydown", + function (e) { + if (e.keyCode == 13) { + toggleFullScreen(); + } + }, + false, +); ``` ### 切换全屏模式 @@ -117,15 +121,15 @@ function toggleFullScreen() { 目前并不是所有的浏览器都实现了 API 的无前缀版本(你可以使用 [Fscreen](https://github.com/rafrex/fscreen) 获取跨浏览器全屏 API),这里有一份表格总结了前缀和它们之间的命名区别: -| Standard | WebKit (Safari) / Blink (Chrome & Opera) / Edge | Gecko (Firefox) | Internet Explorer | -| ------------------------------------------------------------------------- | ----------------------------------------------- | ------------------------ | ----------------------- | +| Standard | WebKit (Safari) / Blink (Chrome & Opera) / Edge | Gecko (Firefox) | Internet Explorer | +| -------------------------------------------------------- | ----------------------------------------------- | ------------------------ | ----------------------- | | {{DOMxRef("Document.fullscreen")}} {{Deprecated_Inline}} | `webkitIsFullScreen` | `mozFullScreen` | - | -| {{DOMxRef("Document.fullscreenEnabled")}} | `webkitFullscreenEnabled` | `mozFullScreenEnabled` | `msFullscreenEnabled` | -| {{DOMxRef("DocumentOrShadowRoot.fullscreenElement")}} | `webkitFullscreenElement` | `mozFullScreenElement` | `msFullscreenElement` | -| {{DOMxRef("Document.onfullscreenchange")}} | `onwebkitfullscreenchange` | `onmozfullscreenchange` | `onMSFullscreenChange` | -| {{DOMxRef("Document.onfullscreenerror")}} | `onwebkitfullscreenerror` | `onmozfullscreenerror` | `onMSFullscreenError` | -| {{DOMxRef("Document.exitFullscreen()")}} | `webkitExitFullscreen()` | `mozCancelFullScreen()` | `msExitFullscreen()` | -| {{DOMxRef("Element.requestFullscreen()")}} | `webkitRequestFullscreen()` | `mozRequestFullScreen()` | `msRequestFullscreen()` | +| {{DOMxRef("Document.fullscreenEnabled")}} | `webkitFullscreenEnabled` | `mozFullScreenEnabled` | `msFullscreenEnabled` | +| {{DOMxRef("DocumentOrShadowRoot.fullscreenElement")}} | `webkitFullscreenElement` | `mozFullScreenElement` | `msFullscreenElement` | +| {{DOMxRef("Document.onfullscreenchange")}} | `onwebkitfullscreenchange` | `onmozfullscreenchange` | `onMSFullscreenChange` | +| {{DOMxRef("Document.onfullscreenerror")}} | `onwebkitfullscreenerror` | `onmozfullscreenerror` | `onMSFullscreenError` | +| {{DOMxRef("Document.exitFullscreen()")}} | `webkitExitFullscreen()` | `mozCancelFullScreen()` | `msExitFullscreen()` | +| {{DOMxRef("Element.requestFullscreen()")}} | `webkitRequestFullscreen()` | `mozRequestFullScreen()` | `msRequestFullscreen()` | ## 规范 diff --git a/files/zh-cn/web/api/fullscreen_api/index.md b/files/zh-cn/web/api/fullscreen_api/index.md index 7f9004091d2876..7e7f1fb7261e5e 100644 --- a/files/zh-cn/web/api/fullscreen_api/index.md +++ b/files/zh-cn/web/api/fullscreen_api/index.md @@ -104,11 +104,15 @@ Fullscreen API 定义了两个事件,可用于检测全屏模式的打开和 当页面加载时,这段代码会运行,设置一个事件监听器以监听 Enter 键。 ```js -document.addEventListener("keydown", function(e) { - if (e.keyCode == 13) { - toggleFullScreen(); - } -}, false); +document.addEventListener( + "keydown", + function (e) { + if (e.keyCode == 13) { + toggleFullScreen(); + } + }, + false, +); ``` ### 切换全屏模式 @@ -118,7 +122,7 @@ document.addEventListener("keydown", function(e) { ```js function toggleFullScreen() { if (!document.fullscreenElement) { - document.documentElement.requestFullscreen(); + document.documentElement.requestFullscreen(); } else { if (document.exitFullscreen) { document.exitFullscreen(); diff --git a/files/zh-cn/web/api/gamepad/index.md b/files/zh-cn/web/api/gamepad/index.md index 2897213a0604da..ddf8f183ec777d 100644 --- a/files/zh-cn/web/api/gamepad/index.md +++ b/files/zh-cn/web/api/gamepad/index.md @@ -37,10 +37,14 @@ Gamepad 对象有两种方式返回值:通过 [`gamepadconnected`](/zh-CN/docs ## 示例 ```js -window.addEventListener("gamepadconnected", function(e) { - console.log("控制器已连接与 %d 位:%s. %d 个按钮,%d 个坐标方向。", - e.gamepad.index, e.gamepad.id, - e.gamepad.buttons.length, e.gamepad.axes.length); +window.addEventListener("gamepadconnected", function (e) { + console.log( + "控制器已连接与 %d 位:%s. %d 个按钮,%d 个坐标方向。", + e.gamepad.index, + e.gamepad.id, + e.gamepad.buttons.length, + e.gamepad.axes.length, + ); }); ``` diff --git a/files/zh-cn/web/api/gamepad_api/using_the_gamepad_api/index.md b/files/zh-cn/web/api/gamepad_api/using_the_gamepad_api/index.md index 21fec717cd0261..4e780d59070a20 100644 --- a/files/zh-cn/web/api/gamepad_api/using_the_gamepad_api/index.md +++ b/files/zh-cn/web/api/gamepad_api/using_the_gamepad_api/index.md @@ -18,10 +18,14 @@ HTML5 为丰富的交互式游戏开发引入了许多必要的组件。像 ` 0 || gp.buttons[0].pressed == true) { + if (gp.buttons[0].value > 0 || gp.buttons[0].pressed == true) { b--; - } else if(gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) { + } else if (gp.buttons[1].value > 0 || gp.buttons[1].pressed == true) { a++; - } else if(gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) { + } else if (gp.buttons[2].value > 0 || gp.buttons[2].pressed == true) { b++; - } else if(gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) { + } else if (gp.buttons[3].value > 0 || gp.buttons[3].pressed == true) { a--; } } - ball.style.left = a*2 + "px"; - ball.style.top = b*2 + "px"; + ball.style.left = a * 2 + "px"; + ball.style.top = b * 2 + "px"; var start = rAF(gameLoop); -}; +} ``` ## 规范 diff --git a/files/zh-cn/web/api/gamepadbutton/pressed/index.md b/files/zh-cn/web/api/gamepadbutton/pressed/index.md index 7f428a7670870f..c5bda0da4f9b4e 100644 --- a/files/zh-cn/web/api/gamepadbutton/pressed/index.md +++ b/files/zh-cn/web/api/gamepadbutton/pressed/index.md @@ -18,7 +18,7 @@ var isPressed = navigator.getGamepads()[0].pressed; ```js var gp = navigator.getGamepads()[0]; // 获取第一个控制器对象 -if(gp.buttons[0].pressed == true) { +if (gp.buttons[0].pressed == true) { // 响应按钮按下 } ``` diff --git a/files/zh-cn/web/api/gamepadbutton/value/index.md b/files/zh-cn/web/api/gamepadbutton/value/index.md index 5e625d79644bda..60fa020eb55b74 100644 --- a/files/zh-cn/web/api/gamepadbutton/value/index.md +++ b/files/zh-cn/web/api/gamepadbutton/value/index.md @@ -21,7 +21,7 @@ var pressState = navigator.getGamepads()[0].value; ```js var gp = navigator.getGamepads()[0]; -if(gp.buttons[0].value > 0) { +if (gp.buttons[0].value > 0) { // 响应模拟按钮被按下 } ``` diff --git a/files/zh-cn/web/api/gamepadevent/gamepad/index.md b/files/zh-cn/web/api/gamepadevent/gamepad/index.md index 599d1c305057a2..12ab1dff3b698c 100644 --- a/files/zh-cn/web/api/gamepadevent/gamepad/index.md +++ b/files/zh-cn/web/api/gamepadevent/gamepad/index.md @@ -18,10 +18,14 @@ slug: Web/API/GamepadEvent/gamepad 在触发的 {{domxref("Window.gamepadconnected")}} 事件上调用 `gamepad` 属性。 ```js -window.addEventListener("gamepadconnected", function(e) { - console.log("控制器已连接于 %d 位:%s. %d 个按钮,%d 个坐标方向。", - e.gamepad.index, e.gamepad.id, - e.gamepad.buttons.length, e.gamepad.axes.length); +window.addEventListener("gamepadconnected", function (e) { + console.log( + "控制器已连接于 %d 位:%s. %d 个按钮,%d 个坐标方向。", + e.gamepad.index, + e.gamepad.id, + e.gamepad.buttons.length, + e.gamepad.axes.length, + ); }); ``` diff --git a/files/zh-cn/web/api/gamepadevent/index.md b/files/zh-cn/web/api/gamepadevent/index.md index 7b315bb66dae5a..d95ea86caf357d 100644 --- a/files/zh-cn/web/api/gamepadevent/index.md +++ b/files/zh-cn/web/api/gamepadevent/index.md @@ -22,19 +22,22 @@ Gamepad API 的 GamepadEvent 接口包含对连接到系统的控制器的引用 在触发的 {{domxref("Window.gamepadconnected")}} 事件上调用控制器属性。 ```js -window.addEventListener("gamepadconnected", function(e) { - console.log("控制器已连接于 %d 位:%s。 %d 个按键,%d 个坐标方向。", - e.gamepad.index, e.gamepad.id, - e.gamepad.buttons.length, e.gamepad.axes.length); +window.addEventListener("gamepadconnected", function (e) { + console.log( + "控制器已连接于 %d 位:%s。 %d 个按键,%d 个坐标方向。", + e.gamepad.index, + e.gamepad.id, + e.gamepad.buttons.length, + e.gamepad.axes.length, + ); }); ``` 与 {{domxref("Window.gamepaddisconnected")}} 事件上的。 ```js -window.addEventListener("gamepaddisconnected", function(e) { - console.log("控制器已从 %d 位断开:%s", - e.gamepad.index, e.gamepad.id); +window.addEventListener("gamepaddisconnected", function (e) { + console.log("控制器已从 %d 位断开:%s", e.gamepad.index, e.gamepad.id); }); ``` diff --git a/files/zh-cn/web/api/geolocation/clearwatch/index.md b/files/zh-cn/web/api/geolocation/clearwatch/index.md index ada25b572e0787..01a1e3be07aa98 100644 --- a/files/zh-cn/web/api/geolocation/clearwatch/index.md +++ b/files/zh-cn/web/api/geolocation/clearwatch/index.md @@ -27,24 +27,24 @@ function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { - console.log('Congratulation, you reach the target'); + console.log("Congratulation, you reach the target"); navigator.geolocation.clearWatch(id); } -}; +} function error(err) { - console.warn('ERROR(' + err.code + '): ' + err.message); -}; + console.warn("ERROR(" + err.code + "): " + err.message); +} target = { - latitude : 0, + latitude: 0, longitude: 0, -} +}; options = { enableHighAccuracy: false, timeout: 5000, - maximumAge: 0 + maximumAge: 0, }; id = navigator.geolocation.watchPosition(success, error, options); diff --git a/files/zh-cn/web/api/geolocation/getcurrentposition/index.md b/files/zh-cn/web/api/geolocation/getcurrentposition/index.md index e69a6d3c3fb0c2..4cd586cd7c9279 100644 --- a/files/zh-cn/web/api/geolocation/getcurrentposition/index.md +++ b/files/zh-cn/web/api/geolocation/getcurrentposition/index.md @@ -28,21 +28,21 @@ navigator.geolocation.getCurrentPosition(success, error, options) var options = { enableHighAccuracy: true, timeout: 5000, - maximumAge: 0 + maximumAge: 0, }; function success(pos) { var crd = pos.coords; - console.log('Your current position is:'); - console.log('Latitude : ' + crd.latitude); - console.log('Longitude: ' + crd.longitude); - console.log('More or less ' + crd.accuracy + ' meters.'); -}; + console.log("Your current position is:"); + console.log("Latitude : " + crd.latitude); + console.log("Longitude: " + crd.longitude); + console.log("More or less " + crd.accuracy + " meters."); +} function error(err) { - console.warn('ERROR(' + err.code + '): ' + err.message); -}; + console.warn("ERROR(" + err.code + "): " + err.message); +} navigator.geolocation.getCurrentPosition(success, error, options); ``` diff --git a/files/zh-cn/web/api/geolocation/watchposition/index.md b/files/zh-cn/web/api/geolocation/watchposition/index.md index 5a81004bfd5484..dc44fca1299e96 100644 --- a/files/zh-cn/web/api/geolocation/watchposition/index.md +++ b/files/zh-cn/web/api/geolocation/watchposition/index.md @@ -35,24 +35,24 @@ function success(pos) { var crd = pos.coords; if (target.latitude === crd.latitude && target.longitude === crd.longitude) { - console.log('Congratulations, you reached the target'); + console.log("Congratulations, you reached the target"); navigator.geolocation.clearWatch(id); } } function error(err) { - console.warn('ERROR(' + err.code + '): ' + err.message); + console.warn("ERROR(" + err.code + "): " + err.message); } target = { - latitude : 0, - longitude: 0 + latitude: 0, + longitude: 0, }; options = { enableHighAccuracy: false, timeout: 5000, - maximumAge: 0 + maximumAge: 0, }; id = navigator.geolocation.watchPosition(success, error, options); diff --git a/files/zh-cn/web/api/geolocation_api/using_the_geolocation_api/index.md b/files/zh-cn/web/api/geolocation_api/using_the_geolocation_api/index.md index 25adba44d2276c..dc790cae0eaaef 100644 --- a/files/zh-cn/web/api/geolocation_api/using_the_geolocation_api/index.md +++ b/files/zh-cn/web/api/geolocation_api/using_the_geolocation_api/index.md @@ -14,7 +14,7 @@ slug: Web/API/Geolocation_API/Using_the_Geolocation_API 如果该对象存在,那么地理位置服务可用。你可以测试 `geolocation` 是否存在: ```js -if ('geolocation' in navigator) { +if ("geolocation" in navigator) { /* geolocation 存在 */ } else { /* geolocation 不存在 */ @@ -67,13 +67,13 @@ function success(position) { } function error() { - alert('Sorry, no position available.'); + alert("Sorry, no position available."); } const options = { enableHighAccuracy: true, maximumAge: 30000, - timeout: 27000 + timeout: 27000, }; const watchID = navigator.geolocation.watchPosition(success, error, options); @@ -89,7 +89,7 @@ const watchID = navigator.geolocation.watchPosition(success, error, options); ```js function success(position) { - const latitude = position.coords.latitude; + const latitude = position.coords.latitude; const longitude = position.coords.longitude; // 使用 latitude 和 longitude 做些什么 @@ -107,7 +107,7 @@ function success(position) { ```js function errorCallback(error) { alert(`ERROR(${error.code}): ${error.message}`); -}; +} ``` ## 示例 @@ -117,56 +117,54 @@ function errorCallback(error) { ```css hidden body { padding: 20px; - background-color:#ffffc9 + background-color: #ffffc9; } button { - margin: .5rem 0; + margin: 0.5rem 0; } ``` ### HTML ```html -
-

- +
+

+ ``` ### JavaScript ```js function geoFindMe() { + const status = document.querySelector("#status"); + const mapLink = document.querySelector("#map-link"); - const status = document.querySelector('#status'); - const mapLink = document.querySelector('#map-link'); - - mapLink.href = ''; - mapLink.textContent = ''; + mapLink.href = ""; + mapLink.textContent = ""; function success(position) { - const latitude = position.coords.latitude; + const latitude = position.coords.latitude; const longitude = position.coords.longitude; - status.textContent = ''; + status.textContent = ""; mapLink.href = `https://www.openstreetmap.org/#map=18/${latitude}/${longitude}`; mapLink.textContent = `纬度:${latitude} °,经度:${longitude} °`; } function error() { - status.textContent = '无法获取你的位置'; + status.textContent = "无法获取你的位置"; } if (!navigator.geolocation) { - status.textContent = '你的浏览器不支持地理位置'; + status.textContent = "你的浏览器不支持地理位置"; } else { - status.textContent = '定位中……'; + status.textContent = "定位中……"; navigator.geolocation.getCurrentPosition(success, error); } - } -document.querySelector('#find-me').addEventListener('click', geoFindMe); +document.querySelector("#find-me").addEventListener("click", geoFindMe); ``` ### 结果 diff --git a/files/zh-cn/web/api/geolocationpositionerror/index.md b/files/zh-cn/web/api/geolocationpositionerror/index.md index 0f0b02aa504e99..59ea0368aac9ae 100644 --- a/files/zh-cn/web/api/geolocationpositionerror/index.md +++ b/files/zh-cn/web/api/geolocationpositionerror/index.md @@ -15,10 +15,10 @@ _`PositionError` 接口没有继承任何属性。_ - : 返回无符号的、简短的错误码。下列值是可能的: - | 值 | 相关联的常量 | 描述 | - | --- | ---------------------- | ------------------------------------------------------------------------------------------------------------- | - | `1` | `PERMISSION_DENIED` | 地理位置信息的获取失败,因为该页面没有获取地理位置信息的权限。 | - | `2` | `POSITION_UNAVAILABLE` | 地理位置获取失败,因为至少有一个内部位置源返回一个内部错误。 | + | 值 | 相关联的常量 | 描述 | + | --- | ---------------------- | ----------------------------------------------------------------------------------------------- | + | `1` | `PERMISSION_DENIED` | 地理位置信息的获取失败,因为该页面没有获取地理位置信息的权限。 | + | `2` | `POSITION_UNAVAILABLE` | 地理位置获取失败,因为至少有一个内部位置源返回一个内部错误。 | | `3` | `TIMEOUT` | 获取地理位置超时,通过定义{{domxref("PositionOptions.timeout")}} 来设置获取地理位置的超时时长。 | - {{domxref("PositionError.message")}} {{readonlyInline}} diff --git a/files/zh-cn/web/api/hashchangeevent/index.md b/files/zh-cn/web/api/hashchangeevent/index.md index f37832604817b3..b95c1bcc936741 100644 --- a/files/zh-cn/web/api/hashchangeevent/index.md +++ b/files/zh-cn/web/api/hashchangeevent/index.md @@ -37,7 +37,7 @@ window.onhashchange = funcRef; **或** ```html - + ``` **或** @@ -50,12 +50,12 @@ window.addEventListener("hashchange", funcRef, false); ```js function locationHashChanged() { - if (location.hash === '#somecoolfeature') { + if (location.hash === "#somecoolfeature") { somecoolfeature(); } } -window.addEventListener('hashchange', locationHashChanged); +window.addEventListener("hashchange", locationHashChanged); ``` ## 回落方法(Polyfill) @@ -63,34 +63,32 @@ window.addEventListener('hashchange', locationHashChanged); 在 [Modernizr GitHub page](https://github.com/Modernizr/Modernizr/wiki/HTML5-Cross-Browser-Polyfills) 中列出了几种回落(fallback)脚本。基本上,这些脚本每隔一段时间检查以此 {{domxref("HTMLHyperlinkElementUtils.hash", "location.hash")}}。这里是其中一个版本,其仅允许一个处理程序(handler)绑定在 {{domxref("Window/hashchange_event", "onhashchange")}} 属性上: ```js -(function(window) { - +(function (window) { // 如果浏览器已经实现了此事件,则退出函数 - if ( "onhashchange" in window.document.body ) return; + if ("onhashchange" in window.document.body) return; var location = window.location, - oldURL = location.href, - oldHash = location.hash; + oldURL = location.href, + oldHash = location.hash; // 每隔 100 毫秒,检查一次片段标识符 - setInterval(function() { - var newURL = location.href, - newHash = location.hash; + setInterval(function () { + var newURL = location.href, + newHash = location.hash; // 如果片段标识符有变化,且处理程序存在 - if ( newHash != oldHash && typeof window.onhashchange === "function" ) { + if (newHash != oldHash && typeof window.onhashchange === "function") { // 执行处理程序 window.onhashchange({ type: "hashchange", oldURL: oldURL, - newURL: newURL + newURL: newURL, }); oldURL = newURL; oldHash = newHash; } }, 100); - })(window); ``` diff --git a/files/zh-cn/web/api/hashchangeevent/newurl/index.md b/files/zh-cn/web/api/hashchangeevent/newurl/index.md index 5c261b1b032b31..2f026cfc0ff357 100644 --- a/files/zh-cn/web/api/hashchangeevent/newurl/index.md +++ b/files/zh-cn/web/api/hashchangeevent/newurl/index.md @@ -20,8 +20,8 @@ let newEventUrl = event.newURL; ## 示例 ```js -window.addEventListener('hashchange', function(event) { - console.log('Hash changed to ' + event.newURL); +window.addEventListener("hashchange", function (event) { + console.log("Hash changed to " + event.newURL); }); ``` diff --git a/files/zh-cn/web/api/hashchangeevent/oldurl/index.md b/files/zh-cn/web/api/hashchangeevent/oldurl/index.md index 09a2cb2f91aa30..a84fad3f7cbee3 100644 --- a/files/zh-cn/web/api/hashchangeevent/oldurl/index.md +++ b/files/zh-cn/web/api/hashchangeevent/oldurl/index.md @@ -20,8 +20,8 @@ let oldEventUrl = event.oldURL; ## 示例 ```js -window.addEventListener('hashchange', function(event) { - console.log('Hash changed from ' + event.oldURL); +window.addEventListener("hashchange", function (event) { + console.log("Hash changed from " + event.oldURL); }); ``` diff --git a/files/zh-cn/web/api/headers/append/index.md b/files/zh-cn/web/api/headers/append/index.md index fc73a2464b0206..bcfbd464a053e7 100644 --- a/files/zh-cn/web/api/headers/append/index.md +++ b/files/zh-cn/web/api/headers/append/index.md @@ -13,8 +13,8 @@ slug: Web/API/Headers/append ## 语法 -```js -myHeaders.append(name,value); +```js-nolint +append(name, value) ``` ### 参数 @@ -39,16 +39,16 @@ var myHeaders = new Headers(); // Currently empty 可以通过 append() 方法添加 header: ```js -myHeaders.append('Content-Type', 'image/jpeg'); -myHeaders.get('Content-Type'); // Returns 'image/jpeg' +myHeaders.append("Content-Type", "image/jpeg"); +myHeaders.get("Content-Type"); // Returns 'image/jpeg' ``` 如果指定 header 不存在,`append()`将会添加这个 header 并赋值 . 如果指定 header 已存在并允许有多个值,`append()`将会把指定值添加到值队列的末尾。 ```js -myHeaders.append('Accept-Encoding', 'deflate'); -myHeaders.append('Accept-Encoding', 'gzip'); -myHeaders.getAll('Accept-Encoding'); // Returns [ "deflate", "gzip" ] +myHeaders.append("Accept-Encoding", "deflate"); +myHeaders.append("Accept-Encoding", "gzip"); +myHeaders.getAll("Accept-Encoding"); // Returns [ "deflate", "gzip" ] ``` 要使用新值覆盖旧值,请使用{{domxref("Headers.set")}}。 diff --git a/files/zh-cn/web/api/headers/delete/index.md b/files/zh-cn/web/api/headers/delete/index.md index 53930025448a40..f6733dd1c6e426 100644 --- a/files/zh-cn/web/api/headers/delete/index.md +++ b/files/zh-cn/web/api/headers/delete/index.md @@ -40,15 +40,15 @@ var myHeaders = new Headers(); // Currently empty 可以通过 append() 方法添加 header: ```js -myHeaders.append('Content-Type', 'image/jpeg'); -myHeaders.get('Content-Type'); // Returns 'image/jpeg' +myHeaders.append("Content-Type", "image/jpeg"); +myHeaders.get("Content-Type"); // Returns 'image/jpeg' ``` 可以通过 delete() 方法删除已有 header: ```js -myHeaders.delete('Content-Type'); -myHeaders.get('Content-Type'); // Returns null, as it has been deleted +myHeaders.delete("Content-Type"); +myHeaders.get("Content-Type"); // Returns null, as it has been deleted ``` ## Specifications diff --git a/files/zh-cn/web/api/headers/entries/index.md b/files/zh-cn/web/api/headers/entries/index.md index b5740f7860a772..f34a0900a2595e 100644 --- a/files/zh-cn/web/api/headers/entries/index.md +++ b/files/zh-cn/web/api/headers/entries/index.md @@ -24,12 +24,12 @@ headers.entries(); ```js // Create a test Headers object var myHeaders = new Headers(); -myHeaders.append('Content-Type', 'text/xml'); -myHeaders.append('Vary', 'Accept-Language'); +myHeaders.append("Content-Type", "text/xml"); +myHeaders.append("Vary", "Accept-Language"); // Display the key/value pairs for (var pair of myHeaders.entries()) { - console.log(pair[0]+ ': '+ pair[1]); + console.log(pair[0] + ": " + pair[1]); } ``` diff --git a/files/zh-cn/web/api/headers/get/index.md b/files/zh-cn/web/api/headers/get/index.md index 3dd0f652743f48..a80f37767d7615 100644 --- a/files/zh-cn/web/api/headers/get/index.md +++ b/files/zh-cn/web/api/headers/get/index.md @@ -35,16 +35,16 @@ var myHeaders = new Headers(); // Currently empty 可以通过 get() 方法来获取 header 中的值: ```js -myHeaders.append('Content-Type', 'image/jpeg'); -myHeaders.get('Content-Type'); // Returns 'image/jpeg' +myHeaders.append("Content-Type", "image/jpeg"); +myHeaders.get("Content-Type"); // Returns 'image/jpeg' ``` 如果存在多个 header 值,那么只有第一个值会被返回: ```js -myHeaders.append('Accept-Encoding', 'deflate'); -myHeaders.append('Accept-Encoding', 'gzip'); -myHeaders.get('Accept-Encoding'); // Returns "deflate,gzip" +myHeaders.append("Accept-Encoding", "deflate"); +myHeaders.append("Accept-Encoding", "gzip"); +myHeaders.get("Accept-Encoding"); // Returns "deflate,gzip" ``` > **备注:** {{domxref("Headers.getAll")}} used to have this functionality, with {{domxref("Headers.get")}} returning only the first value added to the `Headers` object. The latest spec has removed `getAll()`, and updated `get()` to return all values. diff --git a/files/zh-cn/web/api/headers/has/index.md b/files/zh-cn/web/api/headers/has/index.md index 3334c85ea86b53..8879de87ed0a53 100644 --- a/files/zh-cn/web/api/headers/has/index.md +++ b/files/zh-cn/web/api/headers/has/index.md @@ -35,9 +35,9 @@ var myHeaders = new Headers(); // Currently empty 你可以使用 {{domxref("Headers.append")}} 来向 myHeaders 添加一个头信息,然后使用 `has()` 方法来测试是否添加成功: ```js -myHeaders.append('Content-Type', 'image/jpeg'); -myHeaders.has('Content-Type'); // Returns true -myHeaders.has('Accept-Encoding'); // Returns false +myHeaders.append("Content-Type", "image/jpeg"); +myHeaders.has("Content-Type"); // Returns true +myHeaders.has("Accept-Encoding"); // Returns false ``` ## Specifications diff --git a/files/zh-cn/web/api/headers/headers/index.md b/files/zh-cn/web/api/headers/headers/index.md index 00942079a37109..54491d965236a0 100644 --- a/files/zh-cn/web/api/headers/headers/index.md +++ b/files/zh-cn/web/api/headers/headers/index.md @@ -29,14 +29,18 @@ var myHeaders = new Headers(); // Currently empty 你可以使用{{domxref("Headers.append")}}方法添加一个 header 并赋值: ```js -myHeaders.append('Content-Type', 'image/jpeg'); -myHeaders.get('Content-Type'); // Returns 'image/jpeg' +myHeaders.append("Content-Type", "image/jpeg"); +myHeaders.get("Content-Type"); // Returns 'image/jpeg' ``` 或者你可以在 Headers 对象创建时添加多个 header. 在下面的示例中我们创建了一个新的{{domxref("Headers")}} 对象,并通过 Headers 构造函数中 init 属性来添加多个 header: ```js -var httpHeaders = { 'Content-Type' : 'image/jpeg', 'Accept-Charset' : 'utf-8', 'X-My-Custom-Header' : 'Zeke are cool' }; +var httpHeaders = { + "Content-Type": "image/jpeg", + "Accept-Charset": "utf-8", + "X-My-Custom-Header": "Zeke are cool", +}; var myHeaders = new Headers(httpHeaders); ``` @@ -44,7 +48,7 @@ var myHeaders = new Headers(httpHeaders); ```js var secondHeadersObj = new Headers(myHeaders); -secondHeadersObj.get('Content-Type'); // Would return 'image/jpeg' — it inherits it from the first headers object +secondHeadersObj.get("Content-Type"); // Would return 'image/jpeg' — it inherits it from the first headers object ``` ## Specifications diff --git a/files/zh-cn/web/api/headers/index.md b/files/zh-cn/web/api/headers/index.md index 16545dc7ffa9e2..f4c7b01a2ca1df 100644 --- a/files/zh-cn/web/api/headers/index.md +++ b/files/zh-cn/web/api/headers/index.md @@ -57,9 +57,9 @@ slug: Web/API/Headers ```js let myHeaders = new Headers(); -myHeaders.append('Content-Type', 'text/xml'); +myHeaders.append("Content-Type", "text/xml"); -myHeaders.get('Content-Type'); +myHeaders.get("Content-Type"); // should return 'text/xml' ``` diff --git a/files/zh-cn/web/api/headers/keys/index.md b/files/zh-cn/web/api/headers/keys/index.md index c83e6a30184303..d5903d7b28fc8c 100644 --- a/files/zh-cn/web/api/headers/keys/index.md +++ b/files/zh-cn/web/api/headers/keys/index.md @@ -24,12 +24,12 @@ headers.keys(); ```js // 创建一个 Headers 对象 var myHeaders = new Headers(); -myHeaders.append('Content-Type', 'text/xml'); -myHeaders.append('Vary', 'Accept-Language'); +myHeaders.append("Content-Type", "text/xml"); +myHeaders.append("Vary", "Accept-Language"); // 显示 Headers 中所有的 key -for(var key of myHeaders.keys()) { - console.log(key); +for (var key of myHeaders.keys()) { + console.log(key); } ``` diff --git a/files/zh-cn/web/api/headers/set/index.md b/files/zh-cn/web/api/headers/set/index.md index d4a28f572c6eb8..683826e295363e 100644 --- a/files/zh-cn/web/api/headers/set/index.md +++ b/files/zh-cn/web/api/headers/set/index.md @@ -39,16 +39,16 @@ var myHeaders = new Headers(); // Currently empty 你可以用[append()](/zh-CN/docs/Web/API/Headers/append)方法给`Headers` 对象增添一个新的键值对,然后用 **`set()`** 方法去改变这个键值对: ```js -myHeaders.append('Content-Type', 'image/jpeg'); -myHeaders.set('Content-Type', 'text/html'); +myHeaders.append("Content-Type", "image/jpeg"); +myHeaders.set("Content-Type", "text/html"); ``` 如果这个键值对不存在,那么 **`set()`** 方法首先创建一个键值对,然后给它赋值。如果这个键值对存在,那么 **`set()`** 方法将会覆盖之前的 **`value`** 值: ```js -myHeaders.set('Accept-Encoding', 'deflate'); -myHeaders.set('Accept-Encoding', 'gzip'); -myHeaders.get('Accept-Encoding'); // Returns 'gzip' +myHeaders.set("Accept-Encoding", "deflate"); +myHeaders.set("Accept-Encoding", "gzip"); +myHeaders.get("Accept-Encoding"); // Returns 'gzip' ``` 如果你需要增加一个键值对,而不是要覆盖之前的键值对,那么你需要用[append()](/zh-CN/docs/Web/API/Headers/append)方法。 diff --git a/files/zh-cn/web/api/headers/values/index.md b/files/zh-cn/web/api/headers/values/index.md index cb3b007e422896..5ccc39b2f358d4 100644 --- a/files/zh-cn/web/api/headers/values/index.md +++ b/files/zh-cn/web/api/headers/values/index.md @@ -24,12 +24,12 @@ headers.values(); ```js // Create a test Headers object var myHeaders = new Headers(); -myHeaders.append('Content-Type', 'text/xml'); -myHeaders.append('Vary', 'Accept-Language'); +myHeaders.append("Content-Type", "text/xml"); +myHeaders.append("Vary", "Accept-Language"); // Display the values for (var value of myHeaders.values()) { - console.log(value); + console.log(value); } ``` diff --git a/files/zh-cn/web/api/history/back/index.md b/files/zh-cn/web/api/history/back/index.md index eac02188a55710..863f579fd34422 100644 --- a/files/zh-cn/web/api/history/back/index.md +++ b/files/zh-cn/web/api/history/back/index.md @@ -9,8 +9,8 @@ slug: Web/API/History/back ## 语法 -```js -window.history.back() +```js-nolint +back() ``` ## 示例 @@ -26,11 +26,11 @@ window.history.back() ### JavaScript ```js -window.onload = function(e) { - document.getElementById('go-back').addEventListener('click', e => { +window.onload = function (e) { + document.getElementById("go-back").addEventListener("click", (e) => { window.history.back(); - }) -} + }); +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/history/forward/index.md b/files/zh-cn/web/api/history/forward/index.md index 61357541529a68..0fb067e3161357 100644 --- a/files/zh-cn/web/api/history/forward/index.md +++ b/files/zh-cn/web/api/history/forward/index.md @@ -18,17 +18,17 @@ window.history.forward(); ### HTML ```html - + ``` ### JavaScript ```js -window.onload = function(e) { - document.getElementById('go-forward').addEventListener('click', e => { +window.onload = function (e) { + document.getElementById("go-forward").addEventListener("click", (e) => { window.history.forward(); - }) -} + }); +}; ``` ## 规范 diff --git a/files/zh-cn/web/api/history/go/index.md b/files/zh-cn/web/api/history/go/index.md index cf00909c85a0dc..c8e9b1f67668b0 100644 --- a/files/zh-cn/web/api/history/go/index.md +++ b/files/zh-cn/web/api/history/go/index.md @@ -24,13 +24,13 @@ window.history.go(delta); 向后移动一页(等价于调用[`back()`](/zh-CN/docs/Web/API/History/back)): ```js -window.history.go(-1) +window.history.go(-1); ``` 向前移动一页,就像调用了[`forward()`:](/zh-CN/docs/Web/API/History/forward) ```js -window.history.go(1) +window.history.go(1); ``` 向前移动两页: diff --git a/files/zh-cn/web/api/history/scrollrestoration/index.md b/files/zh-cn/web/api/history/scrollrestoration/index.md index 9aeb53979c64ea..f5e2eb6f48e0d8 100644 --- a/files/zh-cn/web/api/history/scrollrestoration/index.md +++ b/files/zh-cn/web/api/history/scrollrestoration/index.md @@ -25,9 +25,11 @@ const scrollRestore = history.scrollRestoration ### 查看当前页面滚动恢复行为 ```js -const scrollRestoration = history.scrollRestoration -if (scrollRestoration === 'manual') { - console.log('The location on the page is not restored, user will need to scroll manually.'); +const scrollRestoration = history.scrollRestoration; +if (scrollRestoration === "manual") { + console.log( + "The location on the page is not restored, user will need to scroll manually.", + ); } ``` @@ -35,7 +37,7 @@ if (scrollRestoration === 'manual') { ```js if (history.scrollRestoration) { - history.scrollRestoration = 'manual'; + history.scrollRestoration = "manual"; } ``` diff --git a/files/zh-cn/web/api/history/state/index.md b/files/zh-cn/web/api/history/state/index.md index 6e00e357750c3b..b48accd692990b 100644 --- a/files/zh-cn/web/api/history/state/index.md +++ b/files/zh-cn/web/api/history/state/index.md @@ -24,7 +24,7 @@ let currentState = history.state; console.log(`History.state before pushState: ${history.state}`); // 现在 push 一些数据到栈里 -history.replaceState({name: 'Example'}, "pushState example", 'page3.html'); +history.replaceState({ name: "Example" }, "pushState example", "page3.html"); // 现在 state 已经有值了 console.log(`History.state after pushState: ${history.state}`); diff --git a/files/zh-cn/web/api/history_api/example/index.md b/files/zh-cn/web/api/history_api/example/index.md index ef263b9099a7c8..044af136e3b72a 100644 --- a/files/zh-cn/web/api/history_api/example/index.md +++ b/files/zh-cn/web/api/history_api/example/index.md @@ -146,22 +146,22 @@ slug: Web/API/History_API/Example ```css #ajax-loader { - position: fixed; - display: table; - top: 0; - left: 0; - width: 100%; - height: 100%; + position: fixed; + display: table; + top: 0; + left: 0; + width: 100%; + height: 100%; } #ajax-loader > div { - display: table-cell; - width: 100%; - height: 100%; - vertical-align: middle; - text-align: center; - background-color: #000000; - opacity: 0.65; + display: table-cell; + width: 100%; + height: 100%; + vertical-align: middle; + text-align: center; + background-color: #000000; + opacity: 0.65; } ``` @@ -196,38 +196,40 @@ slug: Web/API/History_API/Example "use strict"; const ajaxRequest = new (function () { - - function closeReq () { - oLoadingBox.parentNode && document.body.removeChild(oLoadingBox); - bIsLoading = false; - } - - function abortReq () { - if (!bIsLoading) { return; } - oReq.abort(); - closeReq(); - } - - function ajaxError () { - alert("Unknown error."); + function closeReq() { + oLoadingBox.parentNode && document.body.removeChild(oLoadingBox); + bIsLoading = false; + } + + function abortReq() { + if (!bIsLoading) { + return; } - - function ajaxLoad () { - var vMsg, nStatus = this.status; - switch (nStatus) { - case 200: - vMsg = JSON.parse(this.responseText); - document.title = oPageInfo.title = vMsg.page; - document.getElementById(sTargetId).innerHTML = vMsg.content; - if (bUpdateURL) { - history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url); - bUpdateURL = false; - } - break; - default: - vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "Unknown"); - switch (Math.floor(nStatus / 100)) { - /* + oReq.abort(); + closeReq(); + } + + function ajaxError() { + alert("Unknown error."); + } + + function ajaxLoad() { + var vMsg, + nStatus = this.status; + switch (nStatus) { + case 200: + vMsg = JSON.parse(this.responseText); + document.title = oPageInfo.title = vMsg.page; + document.getElementById(sTargetId).innerHTML = vMsg.content; + if (bUpdateURL) { + history.pushState(oPageInfo, oPageInfo.title, oPageInfo.url); + bUpdateURL = false; + } + break; + default: + vMsg = nStatus + ": " + (oHTTPStatus[nStatus] || "Unknown"); + switch (Math.floor(nStatus / 100)) { + /* case 1: // Informational 1xx console.log("Information code " + vMsg); @@ -241,163 +243,190 @@ const ajaxRequest = new (function () { console.log("Redirection code " + vMsg); break; */ - case 4: - /* Client Error 4xx */ - alert("Client Error #" + vMsg); - break; - case 5: - /* Server Error 5xx */ - alert("Server Error #" + vMsg); - break; - default: - /* Unknown status */ - ajaxError(); - } + case 4: + /* Client Error 4xx */ + alert("Client Error #" + vMsg); + break; + case 5: + /* Server Error 5xx */ + alert("Server Error #" + vMsg); + break; + default: + /* Unknown status */ + ajaxError(); } - closeReq(); } - - function filterURL (sURL, sViewMode) { - return sURL.replace(rSearch, "") + ("?" + sURL.replace(rHost, "&").replace(rView, sViewMode ? "&" + sViewKey + "=" + sViewMode : "").slice(1)).replace(rEndQstMark, ""); + closeReq(); + } + + function filterURL(sURL, sViewMode) { + return ( + sURL.replace(rSearch, "") + + ( + "?" + + sURL + .replace(rHost, "&") + .replace(rView, sViewMode ? "&" + sViewKey + "=" + sViewMode : "") + .slice(1) + ).replace(rEndQstMark, "") + ); + } + + function getPage(sPage) { + if (bIsLoading) { + return; } - - function getPage (sPage) { - if (bIsLoading) { return; } - oReq = new XMLHttpRequest(); - bIsLoading = true; - oReq.onload = ajaxLoad; - oReq.onerror = ajaxError; - if (sPage) { oPageInfo.url = filterURL(sPage, null); } - oReq.open("get", filterURL(oPageInfo.url, "json"), true); - oReq.send(); - oLoadingBox.parentNode || document.body.appendChild(oLoadingBox); + oReq = new XMLHttpRequest(); + bIsLoading = true; + oReq.onload = ajaxLoad; + oReq.onerror = ajaxError; + if (sPage) { + oPageInfo.url = filterURL(sPage, null); } - - function requestPage (sURL) { - if (history.pushState) { - bUpdateURL = true; - getPage(sURL); - } else { - /* Ajax navigation is not supported */ - location.assign(sURL); - } - } - - function processLink () { - if (this.className === sAjaxClass) { - requestPage(this.href); - return false; - } - return true; + oReq.open("get", filterURL(oPageInfo.url, "json"), true); + oReq.send(); + oLoadingBox.parentNode || document.body.appendChild(oLoadingBox); + } + + function requestPage(sURL) { + if (history.pushState) { + bUpdateURL = true; + getPage(sURL); + } else { + /* Ajax navigation is not supported */ + location.assign(sURL); } + } - function init () { - oPageInfo.title = document.title; - history.replaceState(oPageInfo, oPageInfo.title, oPageInfo.url); - for (var oLink, nIdx = 0, nLen = document.links.length; nIdx < nLen; document.links[nIdx++].onclick = processLink); + function processLink() { + if (this.className === sAjaxClass) { + requestPage(this.href); + return false; } - - const - - /* customizable constants */ - sTargetId = "ajax-content", sViewKey = "view_as", sAjaxClass = "ajax-nav", - - /* not customizable constants */ - rSearch = /\?.*$/, rHost = /^[^\?]*\?*&*/, rView = new RegExp("&" + sViewKey + "\\=[^&]*|&*$", "i"), rEndQstMark = /\?$/, - oLoadingBox = document.createElement("div"), oCover = document.createElement("div"), oLoadingImg = new Image(), - oPageInfo = { - title: null, - url: location.href - }, oHTTPStatus = /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ { - 100: "Continue", - 101: "Switching Protocols", - 102: "Processing", - 200: "OK", - 201: "Created", - 202: "Accepted", - 203: "Non-Authoritative Information", - 204: "No Content", - 205: "Reset Content", - 206: "Partial Content", - 207: "Multi-Status", - 208: "Already Reported", - 226: "IM Used", - 300: "Multiple Choices", - 301: "Moved Permanently", - 302: "Found", - 303: "See Other", - 304: "Not Modified", - 305: "Use Proxy", - 306: "Reserved", - 307: "Temporary Redirect", - 308: "Permanent Redirect", - 400: "Bad Request", - 401: "Unauthorized", - 402: "Payment Required", - 403: "Forbidden", - 404: "Not Found", - 405: "Method Not Allowed", - 406: "Not Acceptable", - 407: "Proxy Authentication Required", - 408: "Request Timeout", - 409: "Conflict", - 410: "Gone", - 411: "Length Required", - 412: "Precondition Failed", - 413: "Request Entity Too Large", - 414: "Request-URI Too Long", - 415: "Unsupported Media Type", - 416: "Requested Range Not Satisfiable", - 417: "Expectation Failed", - 422: "Unprocessable Entity", - 423: "Locked", - 424: "Failed Dependency", - 425: "Unassigned", - 426: "Upgrade Required", - 427: "Unassigned", - 428: "Precondition Required", - 429: "Too Many Requests", - 430: "Unassigned", - 431: "Request Header Fields Too Large", - 500: "Internal Server Error", - 501: "Not Implemented", - 502: "Bad Gateway", - 503: "Service Unavailable", - 504: "Gateway Timeout", - 505: "HTTP Version Not Supported", - 506: "Variant Also Negotiates (Experimental)", - 507: "Insufficient Storage", - 508: "Loop Detected", - 509: "Unassigned", - 510: "Not Extended", - 511: "Network Authentication Required" - }; - - var - - oReq, bIsLoading = false, bUpdateURL = false; - - oLoadingBox.id = "ajax-loader"; - oCover.onclick = abortReq; - oLoadingImg.src = "data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="; - oCover.appendChild(oLoadingImg); - oLoadingBox.appendChild(oCover); - - onpopstate = function (oEvent) { - bUpdateURL = false; - oPageInfo.title = oEvent.state.title; - oPageInfo.url = oEvent.state.url; - getPage(); - }; - - window.addEventListener ? addEventListener("load", init, false) : window.attachEvent ? attachEvent("onload", init) : (onload = init); - - // Public methods - - this.open = requestPage; - this.stop = abortReq; - this.rebuildLinks = init; - + return true; + } + + function init() { + oPageInfo.title = document.title; + history.replaceState(oPageInfo, oPageInfo.title, oPageInfo.url); + for ( + var oLink, nIdx = 0, nLen = document.links.length; + nIdx < nLen; + document.links[nIdx++].onclick = processLink + ); + } + + const /* customizable constants */ + sTargetId = "ajax-content", + sViewKey = "view_as", + sAjaxClass = "ajax-nav", + /* not customizable constants */ + rSearch = /\?.*$/, + rHost = /^[^\?]*\?*&*/, + rView = new RegExp("&" + sViewKey + "\\=[^&]*|&*$", "i"), + rEndQstMark = /\?$/, + oLoadingBox = document.createElement("div"), + oCover = document.createElement("div"), + oLoadingImg = new Image(), + oPageInfo = { + title: null, + url: location.href, + }, + oHTTPStatus = + /* http://www.iana.org/assignments/http-status-codes/http-status-codes.xml */ { + 100: "Continue", + 101: "Switching Protocols", + 102: "Processing", + 200: "OK", + 201: "Created", + 202: "Accepted", + 203: "Non-Authoritative Information", + 204: "No Content", + 205: "Reset Content", + 206: "Partial Content", + 207: "Multi-Status", + 208: "Already Reported", + 226: "IM Used", + 300: "Multiple Choices", + 301: "Moved Permanently", + 302: "Found", + 303: "See Other", + 304: "Not Modified", + 305: "Use Proxy", + 306: "Reserved", + 307: "Temporary Redirect", + 308: "Permanent Redirect", + 400: "Bad Request", + 401: "Unauthorized", + 402: "Payment Required", + 403: "Forbidden", + 404: "Not Found", + 405: "Method Not Allowed", + 406: "Not Acceptable", + 407: "Proxy Authentication Required", + 408: "Request Timeout", + 409: "Conflict", + 410: "Gone", + 411: "Length Required", + 412: "Precondition Failed", + 413: "Request Entity Too Large", + 414: "Request-URI Too Long", + 415: "Unsupported Media Type", + 416: "Requested Range Not Satisfiable", + 417: "Expectation Failed", + 422: "Unprocessable Entity", + 423: "Locked", + 424: "Failed Dependency", + 425: "Unassigned", + 426: "Upgrade Required", + 427: "Unassigned", + 428: "Precondition Required", + 429: "Too Many Requests", + 430: "Unassigned", + 431: "Request Header Fields Too Large", + 500: "Internal Server Error", + 501: "Not Implemented", + 502: "Bad Gateway", + 503: "Service Unavailable", + 504: "Gateway Timeout", + 505: "HTTP Version Not Supported", + 506: "Variant Also Negotiates (Experimental)", + 507: "Insufficient Storage", + 508: "Loop Detected", + 509: "Unassigned", + 510: "Not Extended", + 511: "Network Authentication Required", + }; + + var oReq, + bIsLoading = false, + bUpdateURL = false; + + oLoadingBox.id = "ajax-loader"; + oCover.onclick = abortReq; + oLoadingImg.src = + "data:image/gif;base64,R0lGODlhEAAQAPIAAP///wAAAMLCwkJCQgAAAGJiYoKCgpKSkiH/C05FVFNDQVBFMi4wAwEAAAAh/hpDcmVhdGVkIHdpdGggYWpheGxvYWQuaW5mbwAh+QQJCgAAACwAAAAAEAAQAAADMwi63P4wyklrE2MIOggZnAdOmGYJRbExwroUmcG2LmDEwnHQLVsYOd2mBzkYDAdKa+dIAAAh+QQJCgAAACwAAAAAEAAQAAADNAi63P5OjCEgG4QMu7DmikRxQlFUYDEZIGBMRVsaqHwctXXf7WEYB4Ag1xjihkMZsiUkKhIAIfkECQoAAAAsAAAAABAAEAAAAzYIujIjK8pByJDMlFYvBoVjHA70GU7xSUJhmKtwHPAKzLO9HMaoKwJZ7Rf8AYPDDzKpZBqfvwQAIfkECQoAAAAsAAAAABAAEAAAAzMIumIlK8oyhpHsnFZfhYumCYUhDAQxRIdhHBGqRoKw0R8DYlJd8z0fMDgsGo/IpHI5TAAAIfkECQoAAAAsAAAAABAAEAAAAzIIunInK0rnZBTwGPNMgQwmdsNgXGJUlIWEuR5oWUIpz8pAEAMe6TwfwyYsGo/IpFKSAAAh+QQJCgAAACwAAAAAEAAQAAADMwi6IMKQORfjdOe82p4wGccc4CEuQradylesojEMBgsUc2G7sDX3lQGBMLAJibufbSlKAAAh+QQJCgAAACwAAAAAEAAQAAADMgi63P7wCRHZnFVdmgHu2nFwlWCI3WGc3TSWhUFGxTAUkGCbtgENBMJAEJsxgMLWzpEAACH5BAkKAAAALAAAAAAQABAAAAMyCLrc/jDKSatlQtScKdceCAjDII7HcQ4EMTCpyrCuUBjCYRgHVtqlAiB1YhiCnlsRkAAAOwAAAAAAAAAAAA=="; + oCover.appendChild(oLoadingImg); + oLoadingBox.appendChild(oCover); + + onpopstate = function (oEvent) { + bUpdateURL = false; + oPageInfo.title = oEvent.state.title; + oPageInfo.url = oEvent.state.url; + getPage(); + }; + + window.addEventListener + ? addEventListener("load", init, false) + : window.attachEvent + ? attachEvent("onload", init) + : (onload = init); + + // Public methods + + this.open = requestPage; + this.stop = abortReq; + this.rebuildLinks = init; })(); ``` diff --git a/files/zh-cn/web/api/history_api/index.md b/files/zh-cn/web/api/history_api/index.md index 6687cab82783bc..1794ff5671510b 100644 --- a/files/zh-cn/web/api/history_api/index.md +++ b/files/zh-cn/web/api/history_api/index.md @@ -48,7 +48,7 @@ window.history.go(1); 您可以通过查看长度属性的值来确定的历史堆栈中页面的数量: ```js - let numberOfEntries = window.history.length; +let numberOfEntries = window.history.length; ``` > **备注:** IE 支持传递 URLs 作为参数给 go();这在 Gecko 是不标准且不支持的。 @@ -64,12 +64,12 @@ HTML5 引入了 [history.pushState()](/zh-CN/docs/Web/API/History/pushState) 和 假设在 `http://mozilla.org/foo.html` 页面的 console 中执行了以下 JavaScript 代码: ```js -window.onpopstate = function(e) { - alert(2); -} +window.onpopstate = function (e) { + alert(2); +}; let stateObj = { - foo: "bar", + foo: "bar", }; history.pushState(stateObj, "page 2", "bar.html"); @@ -125,7 +125,7 @@ history.pushState(stateObj, "page 2", "bar.html"); ```js let stateObj = { - foo: "bar", + foo: "bar", }; history.pushState(stateObj, "page 2", "bar.html"); @@ -154,11 +154,11 @@ history.replaceState(stateObj, "page 3", "bar2.html"); 你可以读取当前历史记录项的状态对象 state,而不必等待`popstate` 事件,只需要这样使用`history.state` 属性: ```js - // 尝试通过 pushState 创建历史条目,然后再刷新页面查看 state 状态对象变化; - window.addEventListener('load',() => { - let currentState = history.state; - console.log('currentState',currentState); - }) +// 尝试通过 pushState 创建历史条目,然后再刷新页面查看 state 状态对象变化; +window.addEventListener("load", () => { + let currentState = history.state; + console.log("currentState", currentState); +}); ``` ## 例子 diff --git a/files/zh-cn/web/api/html_dom_api/index.md b/files/zh-cn/web/api/html_dom_api/index.md index d5193a44c322aa..5dbf69b2dc20dc 100644 --- a/files/zh-cn/web/api/html_dom_api/index.md +++ b/files/zh-cn/web/api/html_dom_api/index.md @@ -301,13 +301,13 @@ History API 接口允许你访问有关浏览器历史记录的信息,并通 ```js const nameField = document.getElementById("userName"); -const sendButton = document.getElementById("sendButton") +const sendButton = document.getElementById("sendButton"); sendButton.disabled = true; // [提示: 这是被禁用的,因为它会导致文章始终加载此示例,并将其聚焦和滚动到视图中] //nameField.focus(); -nameField.addEventListener("input", event => { +nameField.addEventListener("input", (event) => { const elem = event.target; const valid = elem.value.length != 0; @@ -336,13 +336,13 @@ nameField.addEventListener("input", event => {

- (*) + (*)

- +

- + ``` diff --git a/files/zh-cn/web/api/html_dom_api/microtask_guide/index.md b/files/zh-cn/web/api/html_dom_api/microtask_guide/index.md index f861bda8db6485..42c15e15070b36 100644 --- a/files/zh-cn/web/api/html_dom_api/microtask_guide/index.md +++ b/files/zh-cn/web/api/html_dom_api/microtask_guide/index.md @@ -161,7 +161,7 @@ customElement.prototype.getData = url => { ```js const messageQueue = []; -let sendMessage = message => { +let sendMessage = (message) => { messageQueue.push(message); if (messageQueue.length === 1) { @@ -193,15 +193,14 @@ let sendMessage = message => { 在这个简单的例子中,我们将看到入列一个微任务后,会引起其回调函数在顶层脚本完毕后运行。 ```html hidden -
-
+

 ```
 
 #### JavaScript
 
 ```js hidden
 let logElem = document.getElementById("log");
-let log = s => logElem.innerHTML += s + "
"; +let log = (s) => (logElem.innerHTML += s + "
"); ``` 在下面的代码中,我们看到对 {{domxref("queueMicrotask()")}} 的一次调用被用来调度一个微任务以使其运行。这次调用包含了 `log()`,一个简单的向屏幕输出文字的自定义函数。 @@ -209,7 +208,7 @@ let log = s => logElem.innerHTML += s + "
"; ```js log("Before enqueueing the microtask"); queueMicrotask(() => { - log("The microtask has run.") + log("The microtask has run."); }); log("After enqueueing the microtask"); ``` @@ -223,15 +222,14 @@ log("After enqueueing the microtask"); 在这个例子中,一个 timeout 在 0 毫秒后被触发(或者 "尽可能快")。这演示了当调用一个新任务(如通过使用 `setTimeout()`)时的“尽可能快”意味着什么,以及比之于使用一个微任务的不同。 ```html hidden -
-
+

 ```
 
 #### JavaScript
 
 ```js hidden
 let logElem = document.getElementById("log");
-let log = s => logElem.innerHTML += s + "
"; +let log = (s) => (logElem.innerHTML += s + "
"); ``` 在下面的代码中,我们看到对 {{domxref("queueMicrotask()")}} 的一次调用被用来调度一个微任务以使其运行。这次调用包含了 `log()`,一个简单的向屏幕输出文字的自定义函数。 @@ -260,15 +258,14 @@ log("Main program exiting"); 这个例子通过增加一个完成同样工作的函数,略微地扩展了前一个例子。该函数使用 `queueMicrotask()` 调度一个微任务。此例的重要之处是微任务不在其所处的函数退出时,而是在主程序退出时被执行。 ```html hidden -
-
+

 ```
 
 #### JavaScript
 
 ```js hidden
 let logElem = document.getElementById("log");
-let log = s => logElem.innerHTML += s + "
"; +let log = (s) => (logElem.innerHTML += s + "
"); ``` 以下是主程序代码。这里的 `doWork()` 函数调用了 `queueMicrotask()`,但微任务仍在整个程序退出时才触发,因为那才是任务退出而执行栈上为空的时刻。 @@ -283,7 +280,7 @@ let doWork = () => { queueMicrotask(urgentCallback); - for (let i=2; i<=10; i++) { + for (let i = 2; i <= 10; i++) { result *= i; } return result; diff --git a/files/zh-cn/web/api/html_drag_and_drop_api/drag_operations/index.md b/files/zh-cn/web/api/html_drag_and_drop_api/drag_operations/index.md index 9e6928cd85121c..09b91ce1017ad7 100644 --- a/files/zh-cn/web/api/html_drag_and_drop_api/drag_operations/index.md +++ b/files/zh-cn/web/api/html_drag_and_drop_api/drag_operations/index.md @@ -108,7 +108,10 @@ event.dataTransfer.setDragImage(image, xOffset, yOffset); ```js function dragWithCustomImage(event) { - var canvas = document.createElementNS("http://www.w3.org/1999/xhtml","canvas"); + var canvas = document.createElementNS( + "http://www.w3.org/1999/xhtml", + "canvas", + ); canvas.width = canvas.height = 50; var ctx = canvas.getContext("2d"); @@ -120,7 +123,7 @@ function dragWithCustomImage(event) { ctx.stroke(); var dt = event.dataTransfer; - dt.setData('text/plain', 'Data to Drag'); + dt.setData("text/plain", "Data to Drag"); dt.setDragImage(canvas, 25, 25); } ``` @@ -183,8 +186,8 @@ event.dataTransfer.dropEffect = "copy"; 如果你想要允许放置,你必须取消 `dragenter` 和 `dragover` 事件来阻止默认的处理。你可以在属性定义的事件监听程序返回 `false`,或者调用事件的 {{domxref("Event.preventDefault","preventDefault()")}} 方法来实现这一点。在一个独立脚本中的定义的函数里,可能后者更可行。 ```html -
-
+
+
``` 在 {{domxref("HTMLElement/dragenter_event", "dragenter")}} 和 {{domxref("HTMLElement/dragover_event", "dragover")}} 事件中调用 {{domxref("Event.preventDefault","preventDefault()")}} 方法将表明在该位置允许放置。但是,你通常希望只在某些情况下调用 {{domxref("Event.preventDefault","preventDefault()")}} 方法(如只当拖拽的是链接时)。 @@ -195,14 +198,14 @@ event.dataTransfer.dropEffect = "copy"; ```js function contains(list, value) { - for( var i = 0; i < list.length; ++i ) { - if(list[i] === value) return true; - } - return false; + for (var i = 0; i < list.length; ++i) { + if (list[i] === value) return true; + } + return false; } function doDragOver(event) { - var isLink = contains( event.dataTransfer.types, "text/uri-list"); + var isLink = contains(event.dataTransfer.types, "text/uri-list"); if (isLink) { event.preventDefault(); } diff --git a/files/zh-cn/web/api/html_drag_and_drop_api/file_drag_and_drop/index.md b/files/zh-cn/web/api/html_drag_and_drop_api/file_drag_and_drop/index.md index 7cfd7d83fc6474..520a3c6bda4ef0 100644 --- a/files/zh-cn/web/api/html_drag_and_drop_api/file_drag_and_drop/index.md +++ b/files/zh-cn/web/api/html_drag_and_drop_api/file_drag_and_drop/index.md @@ -24,7 +24,10 @@ HTML 拖放接口使得 web 应用能够在网页中拖放文件。这篇文档 一般来说,在实际应用中需要定义一个 [`dragover`](/zh-CN/docs/Web/API/HTMLElement/dragover_event) 事件的处理函数并在其中加入关闭浏览器默认拖放行为的代码。你需要定义一个 {{domxref("GlobalEventHandlers.ondragover","ondragover")}} 事件处理函数: ```html -
+

Drag one or more files to this Drop Zone ...

``` @@ -34,7 +37,7 @@ HTML 拖放接口使得 web 应用能够在网页中拖放文件。这篇文档 ```css #drop_zone { border: 5px solid blue; - width: 200px; + width: 200px; height: 100px; } ``` @@ -51,7 +54,7 @@ HTML 拖放接口使得 web 应用能够在网页中拖放文件。这篇文档 ```js function dropHandler(ev) { - console.log('File(s) dropped'); + console.log("File(s) dropped"); // Prevent default behavior (Prevent file from being opened) ev.preventDefault(); @@ -60,15 +63,17 @@ function dropHandler(ev) { // Use DataTransferItemList interface to access the file(s) for (var i = 0; i < ev.dataTransfer.items.length; i++) { // If dropped items aren't files, reject them - if (ev.dataTransfer.items[i].kind === 'file') { + if (ev.dataTransfer.items[i].kind === "file") { var file = ev.dataTransfer.items[i].getAsFile(); - console.log('... file[' + i + '].name = ' + file.name); + console.log("... file[" + i + "].name = " + file.name); } } } else { // Use DataTransfer interface to access the file(s) for (var i = 0; i < ev.dataTransfer.files.length; i++) { - console.log('... file[' + i + '].name = ' + ev.dataTransfer.files[i].name); + console.log( + "... file[" + i + "].name = " + ev.dataTransfer.files[i].name, + ); } } } @@ -80,7 +85,7 @@ function dropHandler(ev) { ```js function dragOverHandler(ev) { - console.log('File(s) in drop zone'); + console.log("File(s) in drop zone"); // Prevent default behavior (Prevent file from being opened) ev.preventDefault(); diff --git a/files/zh-cn/web/api/html_drag_and_drop_api/index.md b/files/zh-cn/web/api/html_drag_and_drop_api/index.md index cfabac6930fd68..96177af346c0c6 100644 --- a/files/zh-cn/web/api/html_drag_and_drop_api/index.md +++ b/files/zh-cn/web/api/html_drag_and_drop_api/index.md @@ -5,7 +5,7 @@ slug: Web/API/HTML_Drag_and_Drop_API {{DefaultAPISidebar("HTML Drag and Drop API")}} -**HTML 拖放**(Drag and Drop)接口使应用程序能够在浏览器中使用拖放功能。例如,用户可使用鼠标选择可拖拽(*draggable*)元素,将元素拖拽到可放置(*droppable*)元素,并释放鼠标按钮以放置这些元素。拖拽操作期间,会有一个可拖拽元素的半透明快照跟随着鼠标指针。 +**HTML 拖放**(Drag and Drop)接口使应用程序能够在浏览器中使用拖放功能。例如,用户可使用鼠标选择可拖拽(_draggable_)元素,将元素拖拽到可放置(_droppable_)元素,并释放鼠标按钮以放置这些元素。拖拽操作期间,会有一个可拖拽元素的半透明快照跟随着鼠标指针。 对于网站、扩展以及 XUL 应用程序,你可以自定义什么元素是可拖拽的、可拖拽元素产生的反馈类型,以及可放置的元素。 @@ -19,15 +19,15 @@ HTML 的 drag & drop 使用了 {{domxref("Event","DOM event model")}} 以及从 所有的 [拖拽事件类型](/zh-CN/docs/Web/API/DragEvent#Event_types) 有一个对应的 [拖拽全局属性](/zh-CN/docs/Web/API/DragEvent#GlobalEventHandlers)。每个拖拽事件类型和拖拽全局属性都有对应的描述文档。下面的表格提供了一个简短的事件类型描述,以及一个相关文档的链接。 -| 事件 | On 型事件处理程序 | 触发时刻 | -| ---------------------------- | -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------- | -| [`drag`](/zh-CN/docs/Web/API/HTMLElement/drag_event) | {{domxref('GlobalEventHandlers.ondrag','ondrag')}} | 当拖拽元素或选中的文本时触发。 | -| [`dragend`](/zh-CN/docs/Web/API/HTMLElement/dragend_event) | {{domxref('GlobalEventHandlers.ondragend','ondragend')}} | 当拖拽操作结束时触发 (比如松开鼠标按键或敲“Esc”键). (见[结束拖拽](/zh-CN/docs/DragDrop/Drag_Operations#dragend)) | +| 事件 | On 型事件处理程序 | 触发时刻 | +| -------------------------------------------------------------- | ------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------- | +| [`drag`](/zh-CN/docs/Web/API/HTMLElement/drag_event) | {{domxref('GlobalEventHandlers.ondrag','ondrag')}} | 当拖拽元素或选中的文本时触发。 | +| [`dragend`](/zh-CN/docs/Web/API/HTMLElement/dragend_event) | {{domxref('GlobalEventHandlers.ondragend','ondragend')}} | 当拖拽操作结束时触发 (比如松开鼠标按键或敲“Esc”键). (见[结束拖拽](/zh-CN/docs/DragDrop/Drag_Operations#dragend)) | | [`dragenter`](/zh-CN/docs/Web/API/HTMLElement/dragenter_event) | {{domxref('GlobalEventHandlers.ondragenter','ondragenter')}} | 当拖拽元素或选中的文本到一个可释放目标时触发(见 [指定释放目标](/zh-CN/docs/DragDrop/Drag_Operations#droptargets))。 | | [`dragleave`](/zh-CN/docs/Web/API/HTMLElement/dragleave_event) | {{domxref('GlobalEventHandlers.ondragleave','ondragleave')}} | 当拖拽元素或选中的文本离开一个可释放目标时触发。 | -| [`dragover`](/zh-CN/docs/Web/API/HTMLElement/dragover_event) | {{domxref('GlobalEventHandlers.ondragover','ondragover')}} | 当元素或选中的文本被拖到一个可释放目标上时触发(每 100 毫秒触发一次)。 | +| [`dragover`](/zh-CN/docs/Web/API/HTMLElement/dragover_event) | {{domxref('GlobalEventHandlers.ondragover','ondragover')}} | 当元素或选中的文本被拖到一个可释放目标上时触发(每 100 毫秒触发一次)。 | | [`dragstart`](/zh-CN/docs/Web/API/HTMLElement/dragstart_event) | {{domxref('GlobalEventHandlers.ondragstart','ondragstart')}} | 当用户开始拖拽一个元素或选中的文本时触发(见[开始拖拽操作](/zh-CN/docs/DragDrop/Drag_Operations#dragstart))。 | -| [`drop`](/zh-CN/docs/Web/API/HTMLElement/drop_event) | {{domxref('GlobalEventHandlers.ondrop','ondrop')}} | 当元素或选中的文本在可释放目标上被释放时触发(见[执行释放](/zh-CN/docs/DragDrop/Drag_Operations#drop))。 | +| [`drop`](/zh-CN/docs/Web/API/HTMLElement/drop_event) | {{domxref('GlobalEventHandlers.ondrop','ondrop')}} | 当元素或选中的文本在可释放目标上被释放时触发(见[执行释放](/zh-CN/docs/DragDrop/Drag_Operations#drop))。 | **注意:**当从操作系统向浏览器中拖拽文件时,不会触发 `dragstart` 和`dragend` 事件。 @@ -68,7 +68,7 @@ Mozilla 和 Firefox 支持一些不在标准拖放模型中的特性。请查看 ev.dataTransfer.setData("text/plain", ev.target.id); } - window.addEventListener('DOMContentLoaded', () => { + window.addEventListener("DOMContentLoaded", () => { // Get the element by id const element = document.getElementById("p1"); // Add the ondragstart event listener @@ -92,7 +92,10 @@ function dragstart_handler(ev) { // 添加拖拽数据 ev.dataTransfer.setData("text/plain", ev.target.innerText); ev.dataTransfer.setData("text/html", ev.target.outerHTML); - ev.dataTransfer.setData("text/uri-list", ev.target.ownerDocument.location.href); + ev.dataTransfer.setData( + "text/uri-list", + ev.target.ownerDocument.location.href, + ); } ``` @@ -108,7 +111,7 @@ function dragstart_handler(ev) { // NOTE: change "example.gif" to a real image URL or the image // will not be created and the default drag image will be used. var img = new Image(); - img.src = 'example.gif'; + img.src = "example.gif"; ev.dataTransfer.setDragImage(img, 10, 10); } ``` @@ -143,19 +146,24 @@ function dragstart_handler(ev) { ```html -

Drop Zone

+

+ Drop Zone +

``` 注意每个处理程序调用 {{domxref("Event.preventDefault","preventDefault()")}} 来阻止对这个事件的其他处理过程(如触点事件或指针事件)。 @@ -170,25 +178,32 @@ function drop_handler(ev) { ```html -

This element is draggable.

-
Drop Zone
+

+ This element is draggable. +

+
+ Drop Zone +
``` 更多信息请参见 [执行释放](/zh-CN/docs/Web/Guide/HTML/Drag_operations#drop)。 diff --git a/files/zh-cn/web/api/html_drag_and_drop_api/recommended_drag_types/index.md b/files/zh-cn/web/api/html_drag_and_drop_api/recommended_drag_types/index.md index a4e6c7c0469a78..2bd74f660af3da 100644 --- a/files/zh-cn/web/api/html_drag_and_drop_api/recommended_drag_types/index.md +++ b/files/zh-cn/web/api/html_drag_and_drop_api/recommended_drag_types/index.md @@ -119,7 +119,7 @@ Note that the latest spec now dictates that {{domxref("DataTransfer.types")}} sh As a result, the [contains](/zh-CN/docs/Web/API/Node/contains) method no longer works on the property; the [includes](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/includes) method should be used instead to check if a specific type of data is provided, using code like the following: ```js -if ([...event.dataTransfer.types].includes('text/html')) { +if ([...event.dataTransfer.types].includes("text/html")) { // Do something } ``` @@ -167,52 +167,79 @@ There are cases in which you may want to add a file to an existing drag event se currentEvent.dataTransfer.setData("text/x-moz-url", URL); currentEvent.dataTransfer.setData("application/x-moz-file-promise-url", URL); -currentEvent.dataTransfer.setData("application/x-moz-file-promise-dest-filename", leafName); -currentEvent.dataTransfer.mozSetDataAt('application/x-moz-file-promise', - new dataProvider(success,error), - 0, Components.interfaces.nsISupports); - -function dataProvider(){} +currentEvent.dataTransfer.setData( + "application/x-moz-file-promise-dest-filename", + leafName, +); +currentEvent.dataTransfer.mozSetDataAt( + "application/x-moz-file-promise", + new dataProvider(success, error), + 0, + Components.interfaces.nsISupports, +); + +function dataProvider() {} dataProvider.prototype = { - QueryInterface : function(iid) { - if (iid.equals(Components.interfaces.nsIFlavorDataProvider) - || iid.equals(Components.interfaces.nsISupports)) + QueryInterface: function (iid) { + if ( + iid.equals(Components.interfaces.nsIFlavorDataProvider) || + iid.equals(Components.interfaces.nsISupports) + ) return this; throw Components.results.NS_NOINTERFACE; }, - getFlavorData : function(aTransferable, aFlavor, aData, aDataLen) { - if (aFlavor == 'application/x-moz-file-promise') { - - var urlPrimitive = {}; - var dataSize = {}; - - aTransferable.getTransferData('application/x-moz-file-promise-url', urlPrimitive, dataSize); - var url = urlPrimitive.value.QueryInterface(Components.interfaces.nsISupportsString).data; - console.log("URL file orignal is = " + url); - - var namePrimitive = {}; - aTransferable.getTransferData('application/x-moz-file-promise-dest-filename', namePrimitive, dataSize); - var name = namePrimitive.value.QueryInterface(Components.interfaces.nsISupportsString).data; - - console.log("target filename is = " + name); - - var dirPrimitive = {}; - aTransferable.getTransferData('application/x-moz-file-promise-dir', dirPrimitive, dataSize); - var dir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile); - - console.log("target folder is = " + dir.path); - - var file = Cc['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile); - file.initWithPath(dir.path); - file.appendRelativePath(name); - - console.log("output final path is =" + file.path); - - // now you can write or copy the file yourself... + getFlavorData: function (aTransferable, aFlavor, aData, aDataLen) { + if (aFlavor == "application/x-moz-file-promise") { + var urlPrimitive = {}; + var dataSize = {}; + + aTransferable.getTransferData( + "application/x-moz-file-promise-url", + urlPrimitive, + dataSize, + ); + var url = urlPrimitive.value.QueryInterface( + Components.interfaces.nsISupportsString, + ).data; + console.log("URL file orignal is = " + url); + + var namePrimitive = {}; + aTransferable.getTransferData( + "application/x-moz-file-promise-dest-filename", + namePrimitive, + dataSize, + ); + var name = namePrimitive.value.QueryInterface( + Components.interfaces.nsISupportsString, + ).data; + + console.log("target filename is = " + name); + + var dirPrimitive = {}; + aTransferable.getTransferData( + "application/x-moz-file-promise-dir", + dirPrimitive, + dataSize, + ); + var dir = dirPrimitive.value.QueryInterface( + Components.interfaces.nsILocalFile, + ); + + console.log("target folder is = " + dir.path); + + var file = Cc["@mozilla.org/file/local;1"].createInstance( + Components.interfaces.nsILocalFile, + ); + file.initWithPath(dir.path); + file.appendRelativePath(name); + + console.log("output final path is =" + file.path); + + // now you can write or copy the file yourself... } - } -} + }, +}; ``` ## 参见 diff --git a/files/zh-cn/web/api/htmlaudioelement/audio/index.md b/files/zh-cn/web/api/htmlaudioelement/audio/index.md index 6f4eb3340d8c54..159eb49871a365 100644 --- a/files/zh-cn/web/api/htmlaudioelement/audio/index.md +++ b/files/zh-cn/web/api/htmlaudioelement/audio/index.md @@ -37,7 +37,7 @@ audioObj = new Audio(url); 基于事件的方法是最优的: ```js -myAudioElement.addEventListener("canplaythrough", event => { +myAudioElement.addEventListener("canplaythrough", (event) => { /* 音频可以播放;如果权限允许则播放 */ myAudioElement.play(); }); diff --git a/files/zh-cn/web/api/htmlaudioelement/index.md b/files/zh-cn/web/api/htmlaudioelement/index.md index d5ecd348a5de86..8562cb3c9edb73 100644 --- a/files/zh-cn/web/api/htmlaudioelement/index.md +++ b/files/zh-cn/web/api/htmlaudioelement/index.md @@ -40,7 +40,7 @@ _以下方法是未标准化的,请勿使用._ 你可以完全使用 JavaScript 的 {{domxref("HTMLAudioElement.Audio", "Audio()")}} 构造函数来创建一个 `HTMLAudioElement` : ```js -var audioElement = new Audio('car_horn.wav'); +var audioElement = new Audio("car_horn.wav"); ``` 然后你可以在这个元素上调用 `play()` 方法 @@ -54,11 +54,11 @@ audioElement.play(); 一些经常被使用的属性,包括 {{domxref("HTMLMediaElement.src", "src")}}、{{domxref("HTMLMediaElement.currentTime", "currentTime")}}、{{domxref("HTMLMediaElement.duration", "duration")}}、{{domxref("HTMLMediaElement.paused", "paused")}}、{{domxref("HTMLMediaElement.muted", "muted")}} 和 {{domxref("HTMLMediaElement.volume", "volume")}}。以下这段代码赋值音频文件的播放时长给一个变量: ```js -var audioElement = new Audio('car_horn.wav'); -audioElement.addEventListener('loadeddata', () => { +var audioElement = new Audio("car_horn.wav"); +audioElement.addEventListener("loadeddata", () => { let duration = audioElement.duration; // duration 变量现在存放音频的播放时长(单位秒) -}) +}); ``` ## 事件 diff --git a/files/zh-cn/web/api/htmlbuttonelement/index.md b/files/zh-cn/web/api/htmlbuttonelement/index.md index 634acd1477735e..76e7d737e2d420 100644 --- a/files/zh-cn/web/api/htmlbuttonelement/index.md +++ b/files/zh-cn/web/api/htmlbuttonelement/index.md @@ -166,10 +166,10 @@ _从父对象{{domxref("HTMLElement")}}继承的属性。_ _从父对象{{domxref("HTMLElement")}}继承的方法。_ -| 名字 | 返回类型 | 描述 | -| --------------------------------------- | ---------------------------- | ------------------ | +| 名字 | 返回类型 | 描述 | +| --------------------------------------- | ---------------------- | ------------------ | | `checkValidity()` | {{domxref("Boolean")}} | 对按钮元素不支持。 | -| `setCustomValidity(in DOMString error)` | `void` | 对按钮元素不支持。 | +| `setCustomValidity(in DOMString error)` | `void` | 对按钮元素不支持。 | 在基于 Gecko 的浏览器中,在表单验证时会使用{{cssxref(":-moz-submit-invalid")}} 伪类修饰提交按钮。 diff --git a/files/zh-cn/web/api/htmlcanvaselement/capturestream/index.md b/files/zh-cn/web/api/htmlcanvaselement/capturestream/index.md index 05b59752a6732c..125381ed1a8528 100644 --- a/files/zh-cn/web/api/htmlcanvaselement/capturestream/index.md +++ b/files/zh-cn/web/api/htmlcanvaselement/capturestream/index.md @@ -26,7 +26,7 @@ MediaStream = canvas.captureStream(frameRate); ```js //获取所需要截取媒体流的 canvas element -var canvasElt = document.querySelector('canvas'); +var canvasElt = document.querySelector("canvas"); //截取到媒体流 var stream = canvasElt.captureStream(25); // 25 FPS diff --git a/files/zh-cn/web/api/htmlcanvaselement/getcontext/index.md b/files/zh-cn/web/api/htmlcanvaselement/getcontext/index.md index 55988ca4aa1cea..116a1f1cf818e7 100644 --- a/files/zh-cn/web/api/htmlcanvaselement/getcontext/index.md +++ b/files/zh-cn/web/api/htmlcanvaselement/getcontext/index.md @@ -34,9 +34,7 @@ var ctx = canvas.getContext(contextType, contextAttributes); - : 你可以在创建渲染上下文的时候设置多个属性,例如: ```js - canvas.getContext("webgl", - { antialias: false, - depth: false }); + canvas.getContext("webgl", { antialias: false, depth: false }); ``` 2d 上下文属性: diff --git a/files/zh-cn/web/api/htmlcanvaselement/height/index.md b/files/zh-cn/web/api/htmlcanvaselement/height/index.md index 89c5984976a69d..d344337d939327 100644 --- a/files/zh-cn/web/api/htmlcanvaselement/height/index.md +++ b/files/zh-cn/web/api/htmlcanvaselement/height/index.md @@ -27,7 +27,7 @@ canvas.height = pxl; 可以通过以下代码获得这个 canvas 元素的高度: ```js -var canvas = document.getElementById('canvas'); +var canvas = document.getElementById("canvas"); console.log(canvas.height); // 300 ``` diff --git a/files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.md b/files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.md index 3d26511baf9839..b8df10bfe527a1 100644 --- a/files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.md +++ b/files/zh-cn/web/api/htmlcanvaselement/mozopaque/index.md @@ -27,7 +27,7 @@ canvas.mozOpaque = true; 你可以获取或设置 `mozOpaque` 属性。例如,当 mimeType == 'image/jpeg'或类似值时,可以将其属性值设置为 true,以在不需要半透明度的情况下提高应用程序的性能。 ```js -var canvas = document.getElementById('canvas'); +var canvas = document.getElementById("canvas"); console.log(canvas.mozOpaque); // true // 停用该方法 canvas.mozOpaque = false; diff --git a/files/zh-cn/web/api/htmlcanvaselement/toblob/index.md b/files/zh-cn/web/api/htmlcanvaselement/toblob/index.md index b3f47df85bba99..a006b99f96f3f8 100644 --- a/files/zh-cn/web/api/htmlcanvaselement/toblob/index.md +++ b/files/zh-cn/web/api/htmlcanvaselement/toblob/index.md @@ -13,7 +13,9 @@ slug: Web/API/HTMLCanvasElement/toBlob ## 语法 -```js +```js-nolint +toBlob(callback) +toBlob(callback, type) toBlob(callback, type, quality) ``` @@ -44,11 +46,11 @@ toBlob(callback, type, quality) ```js var canvas = document.getElementById("canvas"); -canvas.toBlob(function(blob) { +canvas.toBlob(function (blob) { var newImg = document.createElement("img"), - url = URL.createObjectURL(blob); + url = URL.createObjectURL(blob); - newImg.onload = function() { + newImg.onload = function () { // no longer need to read the blob so it's revoked URL.revokeObjectURL(url); }; @@ -81,17 +83,20 @@ ctx.fillStyle = "yellow"; ctx.fill(); function blobCallback(iconName) { - return function(b) { + return function (b) { var a = document.createElement("a"); a.textContent = "Download"; document.body.appendChild(a); a.style.display = "block"; a.download = iconName + ".ico"; a.href = window.URL.createObjectURL(b); - } + }; } -canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon', - '-moz-parse-options:format=bmp;bpp=32'); +canvas.toBlob( + blobCallback("passThisString"), + "image/vnd.microsoft.icon", + "-moz-parse-options:format=bmp;bpp=32", +); ``` ### 使用 OS.File 保存图像到本地(chrome/add-on context only) @@ -99,42 +104,48 @@ canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon', > **备注:** 此方法可将 toBlob 生成的图片保存到本地,但仅在 Firefox、Chrome 上下文或带有相关插件的情况下可用,因为 Web 并不存在 OS API。 ```js -const canvas = document.getElementById('canvas'); +const canvas = document.getElementById("canvas"); const d = canvas.width; -ctx = canvas.getContext('2d'); +ctx = canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(d / 2, 0); ctx.lineTo(d, d); ctx.lineTo(0, d); ctx.closePath(); -ctx.fillStyle = 'yellow'; +ctx.fillStyle = "yellow"; ctx.fill(); function blobCallback(iconName) { - return function(b) { + return function (b) { const r = new FileReader(); r.onloadend = function () { - // r.result contains the ArrayBuffer. - Cu.import('resource://gre/modules/osfile.jsm'); - const writePath = OS.Path.join(OS.Constants.Path.desktopDir, - iconName + '.ico'); - const promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result), - {tmpPath:writePath + '.tmp'}); - promise.then( - function() { - console.log('successfully wrote file'); - }, - function() { - console.log('failure writing file') - } - ); + // r.result contains the ArrayBuffer. + Cu.import("resource://gre/modules/osfile.jsm"); + const writePath = OS.Path.join( + OS.Constants.Path.desktopDir, + iconName + ".ico", + ); + const promise = OS.File.writeAtomic(writePath, new Uint8Array(r.result), { + tmpPath: writePath + ".tmp", + }); + promise.then( + function () { + console.log("successfully wrote file"); + }, + function () { + console.log("failure writing file"); + }, + ); + }; + r.readAsArrayBuffer(b); }; - r.readAsArrayBuffer(b); - } } -canvas.toBlob(blobCallback('passThisString'), 'image/vnd.microsoft.icon', - '-moz-parse-options:format=bmp;bpp=32'); +canvas.toBlob( + blobCallback("passThisString"), + "image/vnd.microsoft.icon", + "-moz-parse-options:format=bmp;bpp=32", +); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlcanvaselement/todataurl/index.md b/files/zh-cn/web/api/htmlcanvaselement/todataurl/index.md index c25a5c59d9f72a..00c5208a255205 100644 --- a/files/zh-cn/web/api/htmlcanvaselement/todataurl/index.md +++ b/files/zh-cn/web/api/htmlcanvaselement/todataurl/index.md @@ -82,10 +82,14 @@ function showGrayImg() { function removeColors() { var aImages = document.getElementsByClassName("grayscale"), - nImgsLen = aImages.length, - oCanvas = document.createElement("canvas"), - oCtx = oCanvas.getContext("2d"); - for (var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; nImgId < nImgsLen; nImgId++) { + nImgsLen = aImages.length, + oCanvas = document.createElement("canvas"), + oCtx = oCanvas.getContext("2d"); + for ( + var nWidth, nHeight, oImgData, oGrayImg, nPixel, aPix, nPixLen, nImgId = 0; + nImgId < nImgsLen; + nImgId++ + ) { oColorImg = aImages[nImgId]; nWidth = oColorImg.offsetWidth; nHeight = oColorImg.offsetHeight; @@ -96,7 +100,10 @@ function removeColors() { aPix = oImgData.data; nPixLen = aPix.length; for (nPixel = 0; nPixel < nPixLen; nPixel += 4) { - aPix[nPixel + 2] = aPix[nPixel + 1] = aPix[nPixel] = (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3; + aPix[nPixel + 2] = + aPix[nPixel + 1] = + aPix[nPixel] = + (aPix[nPixel] + aPix[nPixel + 1] + aPix[nPixel + 2]) / 3; } oCtx.putImageData(oImgData, 0, 0); oGrayImg = new Image(); diff --git a/files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.md b/files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.md index 14dfd556edefff..e815b870483b9d 100644 --- a/files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.md +++ b/files/zh-cn/web/api/htmlcanvaselement/transfercontroltooffscreen/index.md @@ -20,9 +20,9 @@ OffscreenCanvas HTMLCanvasElement.transferControlToOffscreen() ## 样例 ```js -var htmlCanvas = document.createElement('canvas'); +var htmlCanvas = document.createElement("canvas"); var offscreen = htmlCanvas.transferControlToOffscreen(); -var gl = offscreen.getContext('webgl'); +var gl = offscreen.getContext("webgl"); // ... some drawing using the gl context ... diff --git a/files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.md b/files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.md index a8001489334413..680eb209ba19d2 100644 --- a/files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.md +++ b/files/zh-cn/web/api/htmlcanvaselement/webglcontextlost_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLCanvasElement: webglcontextlost event' +title: "HTMLCanvasElement: webglcontextlost event" slug: Web/API/HTMLCanvasElement/webglcontextlost_event --- @@ -33,15 +33,15 @@ slug: Web/API/HTMLCanvasElement/webglcontextlost_event 在 {{domxref("WEBGL_lose_context")}} 扩展的帮助下,您可以模拟 `webglcontextlost` 事件: ```js -const canvas = document.getElementById('canvas'); -const gl = canvas.getContext('webgl'); +const canvas = document.getElementById("canvas"); +const gl = canvas.getContext("webgl"); -canvas.addEventListener('webglcontextlost', (event) => { +canvas.addEventListener("webglcontextlost", (event) => { console.log(event); }); //WEBGL_lose_context 是 webgl 是属于 WebGLAPI 的一个扩展 API,它提供一组方法用来模拟一个 WebGLRenderingContext 上下文的丢失和恢复。 -gl.getExtension('WEBGL_lose_context').loseContext(); +gl.getExtension("WEBGL_lose_context").loseContext(); // "webglcontextlost" event is logged. ``` diff --git a/files/zh-cn/web/api/htmlcanvaselement/width/index.md b/files/zh-cn/web/api/htmlcanvaselement/width/index.md index eeeb9643913eef..463e75c0f29f28 100644 --- a/files/zh-cn/web/api/htmlcanvaselement/width/index.md +++ b/files/zh-cn/web/api/htmlcanvaselement/width/index.md @@ -27,7 +27,7 @@ canvas.width = pxl; 你能够通过下面的代码得到 canvas 的宽度: ```js -var canvas = document.getElementById('canvas'); +var canvas = document.getElementById("canvas"); console.log(canvas.width); // 300 ``` diff --git a/files/zh-cn/web/api/htmlcollection/index.md b/files/zh-cn/web/api/htmlcollection/index.md index b331ad96da8856..793df3949598af 100644 --- a/files/zh-cn/web/api/htmlcollection/index.md +++ b/files/zh-cn/web/api/htmlcollection/index.md @@ -19,11 +19,13 @@ HTML DOM 中的 `HTMLCollection` 是即时更新的(live);当其所包含 ## 方法 - {{domxref("HTMLCollection.item()")}} + - : 根据给定的索引(从 0 开始),返回具体的节点。如果索引超出了范围,则返回 `null`。 访问 `collection[i]`(在索引 `i` 超出范围时会返回 `undefined`)的替代方法。这在非 JavaScript DOM 的实现中非常有用。 - {{domxref("HTMLCollection.namedItem()")}} + - : 根据 ID 返回指定节点,若不存在,则根据字符串所表示的 `name` 属性来匹配。根据 name 匹配只能作为最后的依赖,并且只有当被引用的元素支持 `name` 属性时才能被匹配。如果不存在符合给定 name 的节点,则返回 `null`。 访问 `collection[name]`(在 `name` 不存在时会返回 `undefined`)的替代方法。这在非 JavaScript DOM 的实现中非常有用。 diff --git a/files/zh-cn/web/api/htmlcollection/item/index.md b/files/zh-cn/web/api/htmlcollection/item/index.md index 12c8ea34996a8b..128ced932312d2 100644 --- a/files/zh-cn/web/api/htmlcollection/item/index.md +++ b/files/zh-cn/web/api/htmlcollection/item/index.md @@ -23,9 +23,9 @@ HTMLCollection 中 `item()` 方法返回一个编号的元素,在 JavaScript ## Example ```js -var c = document.images; // This is an HTMLCollection -var img0 = c.item(0); // You can use the item( ) method this way -var img1 = c[1]; // But this notation is easier and more common +var c = document.images; // This is an HTMLCollection +var img0 = c.item(0); // You can use the item( ) method this way +var img1 = c[1]; // But this notation is easier and more common ``` ## See also diff --git a/files/zh-cn/web/api/htmlcollection/nameditem/index.md b/files/zh-cn/web/api/htmlcollection/nameditem/index.md index 97b3484f90d033..1c3a9c6bdd2cb2 100644 --- a/files/zh-cn/web/api/htmlcollection/nameditem/index.md +++ b/files/zh-cn/web/api/htmlcollection/nameditem/index.md @@ -39,22 +39,22 @@ const item = collection.namedItem(key); ### JavaScript ```js -const container = document.getElementById('personal'); +const container = document.getElementById("personal"); // Returns the HTMLSpanElement with the name "title" if no such element exists null is returned -const titleSpan = container.children.namedItem('title'); +const titleSpan = container.children.namedItem("title"); // The following variants return undefined instead of null if there's no element with a matching name or id -const firstnameSpan = container.children['firstname']; +const firstnameSpan = container.children["firstname"]; const lastnameSpan = container.children.lastname; // Returns the span element with the id "degree" -const degreeSpan = container.children.namedItem('degree'); +const degreeSpan = container.children.namedItem("degree"); -const output = document.createElement('div'); +const output = document.createElement("div"); output.textContent = `Result: ${titleSpan.textContent} ${firstnameSpan.textContent} ${lastnameSpan.textContent} ${degreeSpan.textContent}`; -container.insertAdjacentElement('afterend', output); +container.insertAdjacentElement("afterend", output); ``` {{EmbedLiveSample("示例")}} diff --git a/files/zh-cn/web/api/htmldetailselement/toggle_event/index.md b/files/zh-cn/web/api/htmldetailselement/toggle_event/index.md index 6438efbcd878c5..a4daae2482f5dd 100644 --- a/files/zh-cn/web/api/htmldetailselement/toggle_event/index.md +++ b/files/zh-cn/web/api/htmldetailselement/toggle_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLDetailsElement: toggle event' +title: "HTMLDetailsElement: toggle event" slug: Web/API/HTMLDetailsElement/toggle_event --- @@ -7,11 +7,11 @@ slug: Web/API/HTMLDetailsElement/toggle_event 当{{HtmlElement("details")}}元素`打开`/`关闭`状态被切换时,切换事件会触发。 -| Bubbles | No | -| ---------------------- | ----------------------------------------------------------------------------- | -| Cancelable | No | -| Interface | {{DOMxRef("Event")}} | -| Event handler property | None | +| Bubbles | No | +| ---------------------- | ------------------------------------------------------------------- | +| Cancelable | No | +| Interface | {{DOMxRef("Event")}} | +| Event handler property | None | | Default Action | Toggles the `open` state of the {{HtmlElement("details")}} element. | ## 示例 @@ -31,15 +31,18 @@ slug: Web/API/HTMLDetailsElement/toggle_event Chapter summaries:
Chapter I - Philosophy reproves Boethius for the foolishness of his complaints against Fortune. Her very nature is caprice. + Philosophy reproves Boethius for the foolishness of his complaints against + Fortune. Her very nature is caprice.
Chapter II - Philosophy in Fortune's name replies to Boethius' reproaches, and proves that the gifts of Fortune are hers to give and to take away. + Philosophy in Fortune's name replies to Boethius' reproaches, and proves + that the gifts of Fortune are hers to give and to take away.
Chapter III - Boethius falls back upon his present sense of misery. Philosophy reminds him of the brilliancy of his former fortunes. + Boethius falls back upon his present sense of misery. Philosophy reminds him + of the brilliancy of his former fortunes.
``` @@ -67,12 +70,12 @@ body { ```js function logItem(e) { const item = document.querySelector(`[data-id=${e.target.id}]`); - item.toggleAttribute('hidden'); + item.toggleAttribute("hidden"); } -const chapters = document.querySelectorAll('details'); +const chapters = document.querySelectorAll("details"); chapters.forEach((chapter) => { - chapter.addEventListener('toggle', logItem); + chapter.addEventListener("toggle", logItem); }); ``` diff --git a/files/zh-cn/web/api/htmldialogelement/index.md b/files/zh-cn/web/api/htmldialogelement/index.md index 879de1db11eb5f..a2075006ad3eb1 100644 --- a/files/zh-cn/web/api/htmldialogelement/index.md +++ b/files/zh-cn/web/api/htmldialogelement/index.md @@ -13,19 +13,19 @@ slug: Web/API/HTMLDialogElement _继承自父接口, {{domxref("HTMLElement")}}。_ -| 名称 | 类型 | 描述 | -| ------------- | -------------------------------- | ------------------------------------------------------------------------------------------- | -| `open` | {{domxref("Boolean")}} | 来自[`open`](/zh-CN/docs/Web/HTML/Element/dialog#open) HTML 属性,表示这个对话框可以进行互动。 | -| `returnValue` | {{domxref("DOMString")}} | 用户获取对话框的值 | +| 名称 | 类型 | 描述 | +| ------------- | ------------------------ | ---------------------------------------------------------------------------------------------- | +| `open` | {{domxref("Boolean")}} | 来自[`open`](/zh-CN/docs/Web/HTML/Element/dialog#open) HTML 属性,表示这个对话框可以进行互动。 | +| `returnValue` | {{domxref("DOMString")}} | 用户获取对话框的值 | ## 方法 _继承自父接口, {{domxref("HTMLElement")}}。_ -| 名称和参数 | 类型 | 描述 | -| ------------- | ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `close()` | `void` | 关闭对话框。可选传入类型为 {{domxref("DOMString")}} 的参数,用来更新对话框的 returnValue。 | -| `show()` | `void` | 非模式化的显示这个对话框,即:打开这个对话框之后依然可以和其他内容进行交互。可选传入类型为 {{domxref("Element")}} 或者 {{domxref("MouseEvent")}} 的参数,用来定义对话框的显示位置。 | +| 名称和参数 | 类型 | 描述 | +| ------------- | ------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `close()` | `void` | 关闭对话框。可选传入类型为 {{domxref("DOMString")}} 的参数,用来更新对话框的 returnValue。 | +| `show()` | `void` | 非模式化的显示这个对话框,即:打开这个对话框之后依然可以和其他内容进行交互。可选传入类型为 {{domxref("Element")}} 或者 {{domxref("MouseEvent")}} 的参数,用来定义对话框的显示位置。 | | `showModal()` | `void` | 模式化的显示这个对话框,并且将会至于所有其他对话框的顶层(屏蔽其他对话框的交互)。可选传入类型为{{domxref("Element")}} 或者 {{domxref("MouseEvent")}} 的参数,用来定义对话框的显示位置。 | ## Examples @@ -39,10 +39,12 @@ _继承自父接口, {{domxref("HTMLElement")}}。_
-

"Then art thou glad to seek repose?
- Art glad to leave the sea,
- And anchor all thy weary woes
- In calm Eternity?"

+

+ "Then art thou glad to seek repose?
+ Art glad to leave the sea,
+ And anchor all thy weary woes
+ In calm Eternity?" +

@@ -50,16 +52,15 @@ _继承自父接口, {{domxref("HTMLElement")}}。_ ``` @@ -71,13 +72,15 @@ _继承自父接口, {{domxref("HTMLElement")}}。_
-

-

+

+ + +

@@ -91,20 +94,19 @@ _继承自父接口, {{domxref("HTMLElement")}}。_ ``` diff --git a/files/zh-cn/web/api/htmldialogelement/show/index.md b/files/zh-cn/web/api/htmldialogelement/show/index.md index b0113049760237..a7f4823b2e21aa 100644 --- a/files/zh-cn/web/api/htmldialogelement/show/index.md +++ b/files/zh-cn/web/api/htmldialogelement/show/index.md @@ -26,58 +26,59 @@ Void. The following example shows a simple button that, when clicked, opens a {{htmlelement("dialog")}} containing a form via the `show()` method. From there you can click the _Cancel_ button to close the dialog (via the {{domxref("HTMLDialogElement.close()")}} method), or submit the form via the submit button. ```html - - - -
-

+ +

+ +
+

+

-
- - - - - -
- - - - - - + } + + // Update button opens a modal dialog + updateButton.addEventListener("click", function () { + dialog.showModal(); + openCheck(dialog); + }); + + // Form cancel button closes the dialog box + cancelButton.addEventListener("click", function () { + dialog.close("animalNotChosen"); + openCheck(dialog); + }); + })(); + ``` ## Specifications diff --git a/files/zh-cn/web/api/htmlelement/accesskeylabel/index.md b/files/zh-cn/web/api/htmlelement/accesskeylabel/index.md index 646dadcc6ce689..9b487d8ff6ce63 100644 --- a/files/zh-cn/web/api/htmlelement/accesskeylabel/index.md +++ b/files/zh-cn/web/api/htmlelement/accesskeylabel/index.md @@ -18,16 +18,16 @@ label = element.accessKeyLabel ### JavaScript ```js -var node = document.getElementById('btn1'); +var node = document.getElementById("btn1"); if (node.accessKeyLabel) { - node.title += ' [' + node.accessKeyLabel + ']'; + node.title += " [" + node.accessKeyLabel + "]"; } else { - node.title += ' [' + node.accessKey + ']'; + node.title += " [" + node.accessKey + "]"; } node.onclick = function () { - var p = document.createElement('p'); - p.textContent = 'Clicked!'; + var p = document.createElement("p"); + p.textContent = "Clicked!"; node.parentNode.appendChild(p); }; ``` diff --git a/files/zh-cn/web/api/htmlelement/beforeinput_event/index.md b/files/zh-cn/web/api/htmlelement/beforeinput_event/index.md index c43f8233770063..a59233910ce6bc 100644 --- a/files/zh-cn/web/api/htmlelement/beforeinput_event/index.md +++ b/files/zh-cn/web/api/htmlelement/beforeinput_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLElement: beforeinput event' +title: "HTMLElement: beforeinput event" slug: Web/API/HTMLElement/beforeinput_event --- @@ -49,17 +49,17 @@ In the case of `contenteditable` and `designMode`, the event target is the **edi ### HTML ```html - +

``` ### JavaScript ```js -const input = document.querySelector('input'); -const log = document.getElementById('values'); +const input = document.querySelector("input"); +const log = document.getElementById("values"); -input.addEventListener('beforeinput', updateValue); +input.addEventListener("beforeinput", updateValue); function updateValue(e) { log.textContent = e.target.value; diff --git a/files/zh-cn/web/api/htmlelement/change_event/index.md b/files/zh-cn/web/api/htmlelement/change_event/index.md index 4260b09d183429..1095af632acae1 100644 --- a/files/zh-cn/web/api/htmlelement/change_event/index.md +++ b/files/zh-cn/web/api/htmlelement/change_event/index.md @@ -21,9 +21,9 @@ HTML 标准列出了[应该触发 `change` 事件的 `` 类型](https://h 在方法(如 {{domxref("EventTarget.addEventListener", "addEventListener()")}})中使用事件的名称,或设置事件处理器属性。 ```js -addEventListener('change', (event) => {}); +addEventListener("change", (event) => {}); -onchange = (event) => { }; +onchange = (event) => {}; ``` ## 事件类型 @@ -68,10 +68,10 @@ select { #### JavaScript ```js -const selectElement = document.querySelector('.ice-cream'); +const selectElement = document.querySelector(".ice-cream"); -selectElement.addEventListener('change', (event) => { - const result = document.querySelector('.result'); +selectElement.addEventListener("change", (event) => { + const result = document.querySelector(".result"); result.textContent = `你喜欢 ${event.target.value}`; }); ``` @@ -94,10 +94,10 @@ selectElement.addEventListener('change', (event) => { #### JavaScript ```js -const input = document.querySelector('input'); -const log = document.getElementById('log'); +const input = document.querySelector("input"); +const log = document.getElementById("log"); -input.addEventListener('change', updateValue); +input.addEventListener("change", updateValue); function updateValue(e) { log.textContent = e.target.value; diff --git a/files/zh-cn/web/api/htmlelement/click/index.md b/files/zh-cn/web/api/htmlelement/click/index.md index 12814e8245b826..0ff7eb1e5a003e 100644 --- a/files/zh-cn/web/api/htmlelement/click/index.md +++ b/files/zh-cn/web/api/htmlelement/click/index.md @@ -12,11 +12,11 @@ slug: Web/API/HTMLElement/click ## 语法 -```js -element.click() +```js-nolint +click() ``` -## 用例 +## 示例 当鼠标移动过复选框时模拟一个点击事件: @@ -24,7 +24,11 @@ element.click() ```html
- +
``` diff --git a/files/zh-cn/web/api/htmlelement/dataset/index.md b/files/zh-cn/web/api/htmlelement/dataset/index.md index e224042f78d4ff..f909fd67a261a7 100644 --- a/files/zh-cn/web/api/htmlelement/dataset/index.md +++ b/files/zh-cn/web/api/htmlelement/dataset/index.md @@ -64,7 +64,7 @@ slug: Web/API/HTMLElement/dataset ``` ```js -const el = document.querySelector('#user'); +const el = document.querySelector("#user"); // el.id === 'user' // el.dataset.id === '1234567890' @@ -72,7 +72,7 @@ const el = document.querySelector('#user'); // el.dataset.dateOfBirth === '' // set a data attribute -el.dataset.dateOfBirth = '1960-10-03'; +el.dataset.dateOfBirth = "1960-10-03"; // Result on JS: el.dataset.dateOfBirth === '1960-10-03' // Result on HTML:
John Doe
@@ -80,8 +80,8 @@ delete el.dataset.dateOfBirth; // Result on JS: el.dataset.dateOfBirth === undefined // Result on HTML:
John Doe
-if (!('someDataAttr' in el.dataset)) { - el.dataset.someDataAttr = 'mydata'; +if (!("someDataAttr" in el.dataset)) { + el.dataset.someDataAttr = "mydata"; // Result on JS: 'someDataAttr' in el.dataset === true // Result on HTML:
John Doe
} diff --git a/files/zh-cn/web/api/htmlelement/drag_event/index.md b/files/zh-cn/web/api/htmlelement/drag_event/index.md index 52a8d6205c2dbf..a962fdccca157e 100644 --- a/files/zh-cn/web/api/htmlelement/drag_event/index.md +++ b/files/zh-cn/web/api/htmlelement/drag_event/index.md @@ -12,9 +12,9 @@ slug: Web/API/HTMLElement/drag_event 在类似 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 这样的方法中使用事件名称,或设置事件处理器属性。 ```js -addEventListener('drag', (event) => {}); +addEventListener("drag", (event) => {}); -ondrag = (event) => { }; +ondrag = (event) => {}; ``` ## 事件类型 @@ -38,9 +38,7 @@ _除了下面列出的属性外,还可以使用父接口 {{domxref("Event")}} ```html
-
- 这个 div 可以拖动 -
+
这个 div 可以拖动
``` @@ -71,7 +69,7 @@ body { } .dragging { - opacity: .5; + opacity: 0.5; } ``` @@ -100,10 +98,14 @@ source.addEventListener("dragend", (event) => { /* events fired on the drop targets */ const target = document.getElementById("droptarget"); -target.addEventListener("dragover", (event) => { - // prevent default to allow drop - event.preventDefault(); -}, false); +target.addEventListener( + "dragover", + (event) => { + // prevent default to allow drop + event.preventDefault(); + }, + false, +); target.addEventListener("dragenter", (event) => { // highlight potential drop target when the draggable element enters it diff --git a/files/zh-cn/web/api/htmlelement/dragend_event/index.md b/files/zh-cn/web/api/htmlelement/dragend_event/index.md index 20ff497e28f616..f7f174efd910b9 100644 --- a/files/zh-cn/web/api/htmlelement/dragend_event/index.md +++ b/files/zh-cn/web/api/htmlelement/dragend_event/index.md @@ -15,9 +15,9 @@ original_slug: Web/API/Document/dragend_event 在类似 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 这样的方法中使用事件名称,或设置事件处理器属性。 ```js -addEventListener('dragend', (event) => {}); +addEventListener("dragend", (event) => {}); -ondragend = (event) => { }; +ondragend = (event) => {}; ``` ## 事件类型 @@ -47,9 +47,7 @@ ondragend = (event) => { }; ```html
-
- 这个 div 是可拖动的 -
+
这个 div 是可拖动的
``` @@ -75,7 +73,7 @@ body { } .dragging { - opacity: .5; + opacity: 0.5; } ``` diff --git a/files/zh-cn/web/api/htmlelement/dragenter_event/index.md b/files/zh-cn/web/api/htmlelement/dragenter_event/index.md index c229402ba10ed9..4bd142751b870f 100644 --- a/files/zh-cn/web/api/htmlelement/dragenter_event/index.md +++ b/files/zh-cn/web/api/htmlelement/dragenter_event/index.md @@ -14,9 +14,9 @@ slug: Web/API/HTMLElement/dragenter_event 在 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 等方法中使用事件名称,或者设置事件处理器属性。 ```js -addEventListener('dragenter', (event) => {}); +addEventListener("dragenter", (event) => {}); -ondragenter = (event) => { }; +ondragenter = (event) => {}; ``` ## 事件类型 @@ -27,7 +27,7 @@ ondragenter = (event) => { }; ## 事件属性 -*除了以下的属性,来自父接口 {{domxref("Event")}} 的属性也是可用的。* +_除了以下的属性,来自父接口 {{domxref("Event")}} 的属性也是可用的。_ - {{domxref('DragEvent.dataTransfer')}} {{ReadOnlyInline}} - : 在拖放交互期间转移的数据。 diff --git a/files/zh-cn/web/api/htmlelement/dragleave_event/index.md b/files/zh-cn/web/api/htmlelement/dragleave_event/index.md index c95d339d735d03..e059da4e76bc09 100644 --- a/files/zh-cn/web/api/htmlelement/dragleave_event/index.md +++ b/files/zh-cn/web/api/htmlelement/dragleave_event/index.md @@ -14,9 +14,9 @@ slug: Web/API/HTMLElement/dragleave_event 在类似 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 这样的方法中使用事件名称,或设置事件处理器属性。 ```js -addEventListener('dragleave', (event) => {}); +addEventListener("dragleave", (event) => {}); -ondragleave = (event) => { }; +ondragleave = (event) => {}; ``` ## 事件类型 @@ -46,9 +46,7 @@ _除了下面列出的属性外,还可以使用父接口 {{domxref("Event")}} ```html
-
- 这个 div 可以拖动 -
+
这个 div 可以拖动
``` diff --git a/files/zh-cn/web/api/htmlelement/dragover_event/index.md b/files/zh-cn/web/api/htmlelement/dragover_event/index.md index 9bcc6c0b134d31..d47c0e1df15d6c 100644 --- a/files/zh-cn/web/api/htmlelement/dragover_event/index.md +++ b/files/zh-cn/web/api/htmlelement/dragover_event/index.md @@ -14,9 +14,9 @@ slug: Web/API/HTMLElement/dragover_event 在 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 等方法中使用事件名称,或者设置事件处理器属性。 ```js -addEventListener('dragover', (event) => {}); +addEventListener("dragover", (event) => {}); -ondragover = (event) => { }; +ondragover = (event) => {}; ``` ## 事件类型 diff --git a/files/zh-cn/web/api/htmlelement/dragstart_event/index.md b/files/zh-cn/web/api/htmlelement/dragstart_event/index.md index 193108150459b4..ae1920f8a0d4a6 100644 --- a/files/zh-cn/web/api/htmlelement/dragstart_event/index.md +++ b/files/zh-cn/web/api/htmlelement/dragstart_event/index.md @@ -12,9 +12,9 @@ slug: Web/API/HTMLElement/dragstart_event 在 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 等方法中使用事件名称,或者设置事件处理器属性。 ```js -addEventListener('dragstart', (event) => {}); +addEventListener("dragstart", (event) => {}); -ondragstart = (event) => { }; +ondragstart = (event) => {}; ``` ## 事件类型 diff --git a/files/zh-cn/web/api/htmlelement/drop_event/index.md b/files/zh-cn/web/api/htmlelement/drop_event/index.md index 24349dbe865229..8c439bab49ebd1 100644 --- a/files/zh-cn/web/api/htmlelement/drop_event/index.md +++ b/files/zh-cn/web/api/htmlelement/drop_event/index.md @@ -12,9 +12,9 @@ slug: Web/API/HTMLElement/drop_event 在类似 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 这样的方法中使用事件名称,或设置事件处理器属性。 ```js -addEventListener('drop', (event) => {}); +addEventListener("drop", (event) => {}); -ondrop = (event) => { }; +ondrop = (event) => {}; ``` ## 事件类型 @@ -48,9 +48,7 @@ _除了下面列出的属性外,还可以使用父接口 {{domxref("Event")}} ```html
-
- 这个 div 可以拖动 -
+
这个 div 可以拖动
``` diff --git a/files/zh-cn/web/api/htmlelement/error_event/index.md b/files/zh-cn/web/api/htmlelement/error_event/index.md index e037a2b4659f74..dd4907cfa627b1 100644 --- a/files/zh-cn/web/api/htmlelement/error_event/index.md +++ b/files/zh-cn/web/api/htmlelement/error_event/index.md @@ -72,13 +72,14 @@ body { resize: none; } -label, button { +label, +button { display: block; } button { height: 2rem; - margin: .5rem; + margin: 0.5rem; } img { @@ -90,17 +91,17 @@ img { #### JS ```js -const log = document.querySelector('.event-log-contents'); +const log = document.querySelector(".event-log-contents"); -const badImg = document.querySelector('.bad-img'); -badImg.addEventListener('error', (event) => { - log.textContent = log.textContent + `${event.type}: Loading image\n`; - console.log(event) +const badImg = document.querySelector(".bad-img"); +badImg.addEventListener("error", (event) => { + log.textContent = log.textContent + `${event.type}: Loading image\n`; + console.log(event); }); -const imgError = document.querySelector('#img-error'); -imgError.addEventListener('click', () => { - badImg.setAttribute('src', 'i-dont-exist'); +const imgError = document.querySelector("#img-error"); +imgError.addEventListener("click", () => { + badImg.setAttribute("src", "i-dont-exist"); }); ``` diff --git a/files/zh-cn/web/api/htmlelement/hidden/index.md b/files/zh-cn/web/api/htmlelement/hidden/index.md index 4e6fa2d9a149d7..8e64e4a814ee26 100644 --- a/files/zh-cn/web/api/htmlelement/hidden/index.md +++ b/files/zh-cn/web/api/htmlelement/hidden/index.md @@ -43,11 +43,14 @@ HTMLElement.hidden = true | false; ### JavaScript ```js -document.getElementById("okButton") - .addEventListener("click", function() { - document.getElementById("welcome").hidden = true; - document.getElementById("awesome").hidden = false; -}, false); +document.getElementById("okButton").addEventListener( + "click", + function () { + document.getElementById("welcome").hidden = true; + document.getElementById("awesome").hidden = false; + }, + false, +); ``` 这段代码用来为 welcome 面板中的按钮绑定一个事件监听器,这个事件监听器会隐藏 welcome 面板并在其原位置显示出 follow-up 面板。 @@ -75,9 +78,10 @@ welcome 面板和 follow-up 面板的 HTML 代码。 ```html ``` @@ -87,7 +91,11 @@ welcome 面板和 follow-up 面板的 HTML 代码。 ```css .panel { - font: 16px "Open Sans", Helvetica, Arial, sans-serif; + font: + 16px "Open Sans", + Helvetica, + Arial, + sans-serif; border: 1px solid #22d; padding: 12px; width: 500px; @@ -95,7 +103,11 @@ welcome 面板和 follow-up 面板的 HTML 代码。 } .button { - font: 22px "Open Sans", Helvetica, Arial, sans-serif; + font: + 22px "Open Sans", + Helvetica, + Arial, + sans-serif; padding: 5px 36px; } diff --git a/files/zh-cn/web/api/htmlelement/index.md b/files/zh-cn/web/api/htmlelement/index.md index 274a4f28d0c0bf..8a4de587104cd0 100644 --- a/files/zh-cn/web/api/htmlelement/index.md +++ b/files/zh-cn/web/api/htmlelement/index.md @@ -11,35 +11,35 @@ HTMLElement 接口表示所有的 [HTML](/zh-CN/docs/Web/HTML) 元素。一些 H _继承自父接口 {{domxref("Element")}} 和 {{domxref("GlobalEventHandlers")}} 的属性。_ -| 属性名称 | 属性类型 | Description | -| --------------------------------------------------------------------------------------------------------- | ---------------------------------------------------- | -------------------------------------------------------------------------- | -| {{domxref("HTMLElement.accessKey")}} | {{domxref("DOMString")}} | 获取/设置元素访问的快捷键 | -| {{domxref("HTMLElement.accessKeyLabel")}} | {{domxref("DOMString")}} | 返回一个包含元素访问的快捷键的字符串(只读) | -| {{domxref("HTMLElement.contentEditable")}} | {{domxref("DOMString")}} | 获取/设置元素的可编辑状态 | -| {{domxref("HTMLElement.isContentEditable")}} {{readonlyInline}} | {{domxref("Boolean")}} | 表明元素的内容是否可编辑(只读) | -| {{domxref("HTMLElement.dataset")}} {{readonlyInline}} | {{domxref("DOMStringMap")}} | 获取元素的自定义属性,是一个对象(key-value,只读) | -| {{domxref("HTMLElement.dir")}} | {{domxref("DOMString")}} | 获取/设置元素的方向,可选的值有:ltr,rtl,auto | -| {{domxref("HTMLElement.draggable")}} | {{domxref("Boolean")}} | 设置/获取元素是否可以拖拽 | -| {{domxref("HTMLElement.dropzone")}} {{readonlyInline}} | {{domxref("DOMSettableTokenList")}} | | -| {{domxref("HTMLElement.hidden")}} | {{domxref("Boolean")}} | 获取/设置元素是否隐藏 | -| {{domxref("HTMLElement.itemScope")}} {{experimental_inline}} | {{domxref("Boolean")}} | | -| {{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}} | {{domxref("DOMSettableTokenList")}} | | -| {{domxref("HTMLElement.itemId")}} {{experimental_inline}} | {{domxref("DOMString")}} | | -| {{domxref("HTMLElement.itemRef")}} {{readonlyInline}}{{experimental_inline}} | {{domxref("DOMSettableTokenList")}} | | -| {{domxref("HTMLElement.itemProp")}} {{readonlyInline}}{{experimental_inline}} | {{domxref("DOMSettableTokenList")}} | | -| {{domxref("HTMLElement.itemValue")}} {{experimental_inline}} | {{domxref("object")}} | | -| {{domxref("HTMLElement.lang")}} | {{domxref("DOMString")}} | 获取/设置元素属性、文本、内容的语言 | -| {{domxref("HTMLElement.offsetHeight")}} {{readonlyInline}} | `double` | 元素自身可视高度加上上下 border 的宽度 | -| {{domxref("HTMLElement.offsetLeft")}}{{readonlyInline}} | `double` | 元素自己 border 左边距离父元素 border 左边或者 body 元素 border 左边的距离 | -| {{domxref("HTMLElement.offsetParent")}}{{readonlyInline}} | {{domxref("Element")}} | 元素的父元素,如果没有就是 body 元素 | -| {{domxref("HTMLElement.offsetTop")}}{{readonlyInline}} | `double` | 元素自己 border 顶部距离父元素顶部或者 body 元素 border 顶部的距离 | -| {{domxref("HTMLElement.offsetWidth")}}{{readonlyInline}} | `double` | 元素自身可视宽度加上左右 border 的宽度 | +| 属性名称 | 属性类型 | Description | +| ------------------------------------------------------------------------------- | --------------------------------------- | -------------------------------------------------------------------------- | +| {{domxref("HTMLElement.accessKey")}} | {{domxref("DOMString")}} | 获取/设置元素访问的快捷键 | +| {{domxref("HTMLElement.accessKeyLabel")}} | {{domxref("DOMString")}} | 返回一个包含元素访问的快捷键的字符串(只读) | +| {{domxref("HTMLElement.contentEditable")}} | {{domxref("DOMString")}} | 获取/设置元素的可编辑状态 | +| {{domxref("HTMLElement.isContentEditable")}} {{readonlyInline}} | {{domxref("Boolean")}} | 表明元素的内容是否可编辑(只读) | +| {{domxref("HTMLElement.dataset")}} {{readonlyInline}} | {{domxref("DOMStringMap")}} | 获取元素的自定义属性,是一个对象(key-value,只读) | +| {{domxref("HTMLElement.dir")}} | {{domxref("DOMString")}} | 获取/设置元素的方向,可选的值有:ltr,rtl,auto | +| {{domxref("HTMLElement.draggable")}} | {{domxref("Boolean")}} | 设置/获取元素是否可以拖拽 | +| {{domxref("HTMLElement.dropzone")}} {{readonlyInline}} | {{domxref("DOMSettableTokenList")}} | | +| {{domxref("HTMLElement.hidden")}} | {{domxref("Boolean")}} | 获取/设置元素是否隐藏 | +| {{domxref("HTMLElement.itemScope")}} {{experimental_inline}} | {{domxref("Boolean")}} | | +| {{domxref("HTMLElement.itemType")}} {{readonlyInline}}{{experimental_inline}} | {{domxref("DOMSettableTokenList")}} | | +| {{domxref("HTMLElement.itemId")}} {{experimental_inline}} | {{domxref("DOMString")}} | | +| {{domxref("HTMLElement.itemRef")}} {{readonlyInline}}{{experimental_inline}} | {{domxref("DOMSettableTokenList")}} | | +| {{domxref("HTMLElement.itemProp")}} {{readonlyInline}}{{experimental_inline}} | {{domxref("DOMSettableTokenList")}} | | +| {{domxref("HTMLElement.itemValue")}} {{experimental_inline}} | {{domxref("object")}} | | +| {{domxref("HTMLElement.lang")}} | {{domxref("DOMString")}} | 获取/设置元素属性、文本、内容的语言 | +| {{domxref("HTMLElement.offsetHeight")}} {{readonlyInline}} | `double` | 元素自身可视高度加上上下 border 的宽度 | +| {{domxref("HTMLElement.offsetLeft")}}{{readonlyInline}} | `double` | 元素自己 border 左边距离父元素 border 左边或者 body 元素 border 左边的距离 | +| {{domxref("HTMLElement.offsetParent")}}{{readonlyInline}} | {{domxref("Element")}} | 元素的父元素,如果没有就是 body 元素 | +| {{domxref("HTMLElement.offsetTop")}}{{readonlyInline}} | `double` | 元素自己 border 顶部距离父元素顶部或者 body 元素 border 顶部的距离 | +| {{domxref("HTMLElement.offsetWidth")}}{{readonlyInline}} | `double` | 元素自身可视宽度加上左右 border 的宽度 | | {{domxref("HTMLElement.properties")}} {{readonlyInline}}{{experimental_inline}} | {{domxref("HTMLPropertiesCollection")}} | | -| {{domxref("HTMLElement.spellcheck")}} | {{domxref("Boolean")}} | | -| {{domxref("HTMLElement.style")}} | {{domxref("CSSStyleDeclaration")}} | 获取/设置元素的 style 属性 | -| {{domxref("HTMLElement.tabIndex")}} | `long` | 获取/设置元素的 tab 键控制次序 | -| {{domxref("HTMLElement.title")}} | {{domxref("DOMString")}} | 获取/设置元素的 title 属性 | -| {{domxref("HTMLElement.translate")}} | {{domxref("Boolean")}} | 获取/设置元素是否可以被翻译 | +| {{domxref("HTMLElement.spellcheck")}} | {{domxref("Boolean")}} | | +| {{domxref("HTMLElement.style")}} | {{domxref("CSSStyleDeclaration")}} | 获取/设置元素的 style 属性 | +| {{domxref("HTMLElement.tabIndex")}} | `long` | 获取/设置元素的 tab 键控制次序 | +| {{domxref("HTMLElement.title")}} | {{domxref("DOMString")}} | 获取/设置元素的 title 属性 | +| {{domxref("HTMLElement.translate")}} | {{domxref("Boolean")}} | 获取/设置元素是否可以被翻译 | ## 事件 @@ -58,11 +58,11 @@ Listen to these events using `addEventListener()` or by assigning an event liste _从父元素继承的方法,{{domxref("Element")}}._ -| Name & Arguments | Return | Description | -| --------------------------------------------------------------------------------------------- | ------ | ------------------ | -| {{domxref("HTMLElement.blur()")}} | `void` | 元素失去焦点 | -| {{domxref("HTMLElement.click()")}} | `void` | 触发元素的点击事件 | -| {{domxref("HTMLElement.focus()")}} | `void` | 元素获得焦点 | +| Name & Arguments | Return | Description | +| -------------------------------------------------------------------- | ------ | ------------------ | +| {{domxref("HTMLElement.blur()")}} | `void` | 元素失去焦点 | +| {{domxref("HTMLElement.click()")}} | `void` | 触发元素的点击事件 | +| {{domxref("HTMLElement.focus()")}} | `void` | 元素获得焦点 | | {{domxref("HTMLElement.forceSpellCheck()")}} {{experimental_inline}} | `void` | | ## 规范 diff --git a/files/zh-cn/web/api/htmlelement/input_event/index.md b/files/zh-cn/web/api/htmlelement/input_event/index.md index be0af8f248d9c0..82d3545b425dbd 100644 --- a/files/zh-cn/web/api/htmlelement/input_event/index.md +++ b/files/zh-cn/web/api/htmlelement/input_event/index.md @@ -41,17 +41,17 @@ slug: Web/API/HTMLElement/input_event ### HTML ```html - +

``` ### JavaScript ```js -const input = document.querySelector('input'); -const log = document.getElementById('values'); +const input = document.querySelector("input"); +const log = document.getElementById("values"); -input.addEventListener('input', updateValue); +input.addEventListener("input", updateValue); function updateValue(e) { log.textContent = e.srcElement.value; @@ -64,12 +64,12 @@ function updateValue(e) { ## 属性 -| Property | Type | Description | -| ------------------------------------- | ------------------------------------ | ------------------------------------------------------ | +| Property | Type | Description | +| ------------------------------- | -------------------------- | ------------------------------------------------------ | | `target` {{readonlyInline}} | {{domxref("EventTarget")}} | The event target (the topmost target in the DOM tree). | -| `type` {{readonlyInline}} | {{domxref("DOMString")}} | The type of event. | -| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | Whether the event normally bubbles or not. | -| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | Whether the event is cancellable or not. | +| `type` {{readonlyInline}} | {{domxref("DOMString")}} | The type of event. | +| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | Whether the event normally bubbles or not. | +| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | Whether the event is cancellable or not. | ## 规范 diff --git a/files/zh-cn/web/api/htmlelement/style/index.md b/files/zh-cn/web/api/htmlelement/style/index.md index d829b6a396e018..b831166ed11271 100644 --- a/files/zh-cn/web/api/htmlelement/style/index.md +++ b/files/zh-cn/web/api/htmlelement/style/index.md @@ -34,7 +34,7 @@ slug: Web/API/HTMLElement/style 以下代码片段演示了从元素的 `style` 属性获得的值如何与 HTML 属性上设置的样式相关。 ```html - +
diff --git a/files/zh-cn/web/api/htmlfieldsetelement/index.md b/files/zh-cn/web/api/htmlfieldsetelement/index.md index 395a2d2a4d7de8..6347decddfe533 100644 --- a/files/zh-cn/web/api/htmlfieldsetelement/index.md +++ b/files/zh-cn/web/api/htmlfieldsetelement/index.md @@ -13,20 +13,20 @@ DOM `fieldset` elements expose the [HTMLFieldSetElement](http://dev.w3.org/html5 属性继承自其父级 {{domxref("HTMLElement")}}。 -| 名称 | 类型 | 描述 | -| ------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `disabled` | `Boolean` | 读取 HTML 属性 [`disabled`](/zh-CN/docs/Web/HTML/Element/fieldset#disabled),表明用户是否可以操作该控件。 | -| `elements` | `readonly HTMLFormControlsCollection` | The elements belonging to this field set. | +| 名称 | 类型 | 描述 | +| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `disabled` | `Boolean` | 读取 HTML 属性 [`disabled`](/zh-CN/docs/Web/HTML/Element/fieldset#disabled),表明用户是否可以操作该控件。 | +| `elements` | `readonly HTMLFormControlsCollection` | The elements belonging to this field set. | | `form` {{ReadOnlyInline}} | An {{domxref("HTMLFormControlsCollection")}} or {{domxref("HTMLCollection")}} referencing the containing form element, if this element is in a form. If the field set is not a descendant of a form element, then the attribute can be the ID of any form element in the same document it is related to, or the `null` value if none matches. | | -| `name` | [`DOMString`](/zh-CN/DOM/DOMString) | Reflects the [`name`](/zh-CN/docs/Web/HTML/Element/fieldset#name) HTML attribute, containing the name of the field set, used for submitting the form. | -| `type` | `readonly DOMString` | 一定为字符串`fieldset`. | -| `validationMessage` | `readonly DOMString` | A localized message that describes the validation constraints that the element does not satisfy (if any). This is the empty string if the element is not a candidate for constraint validation (**willValidate** is false), or it satisfies its constraints. | -| `validity` | `readonly ValidityState` | The validity states that this element is in. | -| `willValidate` | `boolean` | Always false because `fieldset` objects are never candidates for constraint validation. | +| `name` | [`DOMString`](/zh-CN/DOM/DOMString) | Reflects the [`name`](/zh-CN/docs/Web/HTML/Element/fieldset#name) HTML attribute, containing the name of the field set, used for submitting the form. | +| `type` | `readonly DOMString` | 一定为字符串`fieldset`. | +| `validationMessage` | `readonly DOMString` | A localized message that describes the validation constraints that the element does not satisfy (if any). This is the empty string if the element is not a candidate for constraint validation (**willValidate** is false), or it satisfies its constraints. | +| `validity` | `readonly ValidityState` | The validity states that this element is in. | +| `willValidate` | `boolean` | Always false because `fieldset` objects are never candidates for constraint validation. | ## 方法 -| 名称 & 参数 | 返回值 | 描述 | -| ----------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------- | -| `checkValidity`() | `Boolean` | 如果元素的值没有有效性问题,则返回 `true`,否则返回 `false` 并触发 `invalid` 事件。 | +| 名称 & 参数 | 返回值 | 描述 | +| ----------------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `checkValidity`() | `Boolean` | 如果元素的值没有有效性问题,则返回 `true`,否则返回 `false` 并触发 `invalid` 事件。 | | `setCustomValidity(in` [DOMString](/zh-CN/DOM/DOMString) `error)` | `void` | 设置一个自定义错误,则该元素将无法通过有效性验证。参数指定的字符串就是在向用户报告错误时显示的消息。如果为空字符串,则清除这个自定义错误。 |