```
@@ -147,25 +189,43 @@ First, create a function that takes the text field and a key event as input and
```js
function checkRows(oField, oKeyEvent) {
- var nKey = (oKeyEvent || /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 }).keyCode,
-
+ var nKey = (
+ oKeyEvent ||
+ /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 }
+ ).keyCode,
// put here the maximum number of characters per line:
nCols = 30,
// put here the maximum number of lines:
nRows = 5,
-
- nSelS = oField.selectionStart, nSelE = oField.selectionEnd,
- sVal = oField.value, nLen = sVal.length,
-
+ nSelS = oField.selectionStart,
+ nSelE = oField.selectionEnd,
+ sVal = oField.value,
+ nLen = sVal.length,
nBackward = nSelS >= nCols ? nSelS - nCols : 0,
- nDeltaForw = sVal.substring(nBackward, nSelS).search(new RegExp("\\n(?!.{0," + String(nCols - 2) + "}\\n)")) + 1,
+ nDeltaForw =
+ sVal
+ .substring(nBackward, nSelS)
+ .search(new RegExp("\\n(?!.{0," + String(nCols - 2) + "}\\n)")) + 1,
nRowStart = nBackward + nDeltaForw,
- aReturns = (sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)).match(/\n/g),
+ aReturns = (
+ sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)
+ ).match(/\n/g),
nRowEnd = nSelE + nRowStart + nCols - nSelS,
- sRow = sVal.substring(nRowStart, nSelS) + sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd),
- bKeepCols = nKey === 13 || nLen + 1 < nCols || /\n/.test(sRow) || ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) && (sRow.length < nCols || (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n"))));
-
- return (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) && ((nKey > 32 && nKey < 41) || bKeepCols);
+ sRow =
+ sVal.substring(nRowStart, nSelS) +
+ sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd),
+ bKeepCols =
+ nKey === 13 ||
+ nLen + 1 < nCols ||
+ /\n/.test(sRow) ||
+ ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) &&
+ (sRow.length < nCols ||
+ (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n"))));
+
+ return (
+ (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) &&
+ ((nKey > 32 && nKey < 41) || bKeepCols)
+ );
}
```
@@ -173,9 +233,13 @@ In the HTML we just need to hook our function to the `onkeypress` event and spec
```html
Some text to copy and paste.
-Go on, try pasting some content into this editable paragraph and see what happens!
+
+ Go on, try pasting some content into this editable paragraph and see what
+ happens!
+
-
Some sample text. Try inserting line breaks, or deleting text in different ways, or pasting different content in.
-
+
Input type:
+
+
+ Some sample text. Try inserting line breaks, or deleting text in different
+ ways, or pasting different content in.
+
+
- A sample
- bulleted
@@ -40,9 +45,9 @@ var aString = inputEvent.inputType;
### JavaScript
```js
-const log = document.getElementById('log');
-const editable = document.querySelector('div[contenteditable]');
-editable.addEventListener('input', logInputType);
+const log = document.getElementById("log");
+const editable = document.querySelector("div[contenteditable]");
+editable.addEventListener("input", logInputType);
function logInputType(event) {
log.textContent = `Input type: ${event.inputType}`;
diff --git a/files/zh-cn/web/api/installevent/index.md b/files/zh-cn/web/api/installevent/index.md
index b447e9c4d67d51..20814147f5356b 100644
--- a/files/zh-cn/web/api/installevent/index.md
+++ b/files/zh-cn/web/api/installevent/index.md
@@ -38,28 +38,38 @@ _从它的父类{{domxref("ExtendableEvent")}}继承方法。_
```js
var CACHE_VERSION = 1;
var CURRENT_CACHES = {
- prefetch: 'prefetch-cache-v' + CACHE_VERSION
+ prefetch: "prefetch-cache-v" + CACHE_VERSION,
};
-self.addEventListener('install', function(event) {
+self.addEventListener("install", function (event) {
var urlsToPrefetch = [
- './static/pre_fetched.txt',
- './static/pre_fetched.html',
- 'https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif'
+ "./static/pre_fetched.txt",
+ "./static/pre_fetched.html",
+ "https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif",
];
-console.log('Handling install event. Resources to pre-fetch:', urlsToPrefetch);
+ console.log(
+ "Handling install event. Resources to pre-fetch:",
+ urlsToPrefetch,
+ );
event.waitUntil(
- caches.open(CURRENT_CACHES['prefetch']).then(function(cache) {
- cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) {
- return new Request(urlToPrefetch, {mode: 'no-cors'});
- })).then(function() {
- console.log('All resources have been fetched and cached.');
- });
- }).catch(function(error) {
- console.error('Pre-fetching failed:', error);
- })
+ caches
+ .open(CURRENT_CACHES["prefetch"])
+ .then(function (cache) {
+ cache
+ .addAll(
+ urlsToPrefetch.map(function (urlToPrefetch) {
+ return new Request(urlToPrefetch, { mode: "no-cors" });
+ }),
+ )
+ .then(function () {
+ console.log("All resources have been fetched and cached.");
+ });
+ })
+ .catch(function (error) {
+ console.error("Pre-fetching failed:", error);
+ }),
);
});
```
diff --git a/files/zh-cn/web/api/intersection_observer_api/index.md b/files/zh-cn/web/api/intersection_observer_api/index.md
index 4537b0a588de50..b6c8431c075459 100644
--- a/files/zh-cn/web/api/intersection_observer_api/index.md
+++ b/files/zh-cn/web/api/intersection_observer_api/index.md
@@ -41,10 +41,10 @@ Intersection Observer API 允许你配置一个回调函数,当以下情况发
```js
let options = {
- root: document.querySelector('#scrollArea'),
- rootMargin: '0px',
- threshold: 1.0
-}
+ root: document.querySelector("#scrollArea"),
+ rootMargin: "0px",
+ threshold: 1.0,
+};
let observer = new IntersectionObserver(callback, options);
```
@@ -67,7 +67,7 @@ let observer = new IntersectionObserver(callback, options);
创建一个 observer 后需要给定一个目标元素进行观察。
```js
-let target = document.querySelector('#listItem');
+let target = document.querySelector("#listItem");
observer.observe(target);
```
@@ -76,8 +76,8 @@ observer.observe(target);
只要目标满足为 IntersectionObserver 指定的阈值,就会调用回调。回调接收 {{domxref("IntersectionObserverEntry")}} 对象和观察者的列表:
```js
-let callback =(entries, observer) => {
- entries.forEach(entry => {
+let callback = (entries, observer) => {
+ entries.forEach((entry) => {
// Each entry describes an intersection change for one observed target element:
// entry.boundingClientRect
// entry.intersectionRatio
@@ -137,8 +137,7 @@ Note that it's possible to have a non-zero intersection rectangle, which can hap
```
@@ -182,7 +181,10 @@ Note that it's possible to have a non-zero intersection rectangle, which can hap
}
.label {
- font: 14px "Open Sans", "Arial", sans-serif;
+ font:
+ 14px "Open Sans",
+ "Arial",
+ sans-serif;
position: absolute;
margin: 0;
background-color: rgba(255, 255, 255, 0.7);
@@ -225,7 +227,7 @@ startup = () => {
let observerOptions = {
root: null,
rootMargin: "0px",
- threshold: []
+ threshold: [],
};
// An array of threshold sets for each of the boxes. The
@@ -237,45 +239,51 @@ startup = () => {
[],
[0.5],
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
- [0, 0.25, 0.5, 0.75, 1.0]
+ [0, 0.25, 0.5, 0.75, 1.0],
];
- for (let i=0; i<=1.0; i+= 0.01) {
+ for (let i = 0; i <= 1.0; i += 0.01) {
thresholdSets[0].push(i);
}
// Add each box, creating a new observer for each
- for (let i=0; i<4; i++) {
- let template = document.querySelector("#boxTemplate").content.cloneNode(true);
- let boxID = "box" + (i+1);
+ for (let i = 0; i < 4; i++) {
+ let template = document
+ .querySelector("#boxTemplate")
+ .content.cloneNode(true);
+ let boxID = "box" + (i + 1);
template.querySelector(".sampleBox").id = boxID;
wrapper.appendChild(document.importNode(template, true));
// Set up the observer for this box
observerOptions.threshold = thresholdSets[i];
- observers[i] = new IntersectionObserver(intersectionCallback, observerOptions);
+ observers[i] = new IntersectionObserver(
+ intersectionCallback,
+ observerOptions,
+ );
observers[i].observe(document.querySelector("#" + boxID));
}
// Scroll to the starting position
- document.scrollingElement.scrollTop = wrapper.firstElementChild.getBoundingClientRect().top + window.scrollY;
+ document.scrollingElement.scrollTop =
+ wrapper.firstElementChild.getBoundingClientRect().top + window.scrollY;
document.scrollingElement.scrollLeft = 750;
-}
+};
intersectionCallback = (entries) => {
entries.forEach((entry) => {
let box = entry.target;
- let visiblePct = (Math.floor(entry.intersectionRatio * 100)) + "%";
+ let visiblePct = Math.floor(entry.intersectionRatio * 100) + "%";
box.querySelector(".topLeft").innerHTML = visiblePct;
box.querySelector(".topRight").innerHTML = visiblePct;
box.querySelector(".bottomLeft").innerHTML = visiblePct;
box.querySelector(".bottomRight").innerHTML = visiblePct;
});
-}
+};
startup();
```
@@ -332,9 +340,7 @@ The HTML for this example is very short, with a primary element which is the box
```html
-
- Welcome to The Box!
-
+
Welcome to The Box!
```
@@ -346,7 +352,9 @@ The CSS isn't terribly important for the purposes of this example; it lays out t
#box {
background-color: rgba(40, 40, 190, 255);
border: 4px solid rgb(20, 20, 120);
- transition: background-color 1s, border 1s;
+ transition:
+ background-color 1s,
+ border 1s;
width: 350px;
height: 350px;
display: flex;
@@ -387,11 +395,15 @@ let increasingColor = "rgba(40, 40, 190, ratio)";
let decreasingColor = "rgba(190, 40, 40, ratio)";
// Set things up
-window.addEventListener("load", (event) => {
- boxElement = document.querySelector("#box");
-
- createObserver();
-}, false);
+window.addEventListener(
+ "load",
+ (event) => {
+ boxElement = document.querySelector("#box");
+
+ createObserver();
+ },
+ false,
+);
```
The constants and variables we set up here are:
@@ -418,7 +430,7 @@ function createObserver() {
let options = {
root: null,
rootMargin: "0px",
- threshold: buildThresholdList()
+ threshold: buildThresholdList(),
};
observer = new IntersectionObserver(handleIntersect, options);
@@ -443,8 +455,8 @@ function buildThresholdList() {
let thresholds = [];
let numSteps = 20;
- for (let i=1.0; i<=numSteps; i++) {
- let ratio = i/numSteps;
+ for (let i = 1.0; i <= numSteps; i++) {
+ let ratio = i / numSteps;
thresholds.push(ratio);
}
@@ -478,9 +490,15 @@ When the browser detects that the target element (in our case, the one with the
function handleIntersect(entries, observer) {
entries.forEach((entry) => {
if (entry.intersectionRatio > prevRatio) {
- entry.target.style.backgroundColor = increasingColor.replace("ratio", entry.intersectionRatio);
+ entry.target.style.backgroundColor = increasingColor.replace(
+ "ratio",
+ entry.intersectionRatio,
+ );
} else {
- entry.target.style.backgroundColor = decreasingColor.replace("ratio", entry.intersectionRatio);
+ entry.target.style.backgroundColor = decreasingColor.replace(
+ "ratio",
+ entry.intersectionRatio,
+ );
}
prevRatio = entry.intersectionRatio;
diff --git a/files/zh-cn/web/api/intersection_observer_api/timing_element_visibility/index.md b/files/zh-cn/web/api/intersection_observer_api/timing_element_visibility/index.md
index 41657c84ef0b7c..594ca60d08b694 100644
--- a/files/zh-cn/web/api/intersection_observer_api/timing_element_visibility/index.md
+++ b/files/zh-cn/web/api/intersection_observer_api/timing_element_visibility/index.md
@@ -34,8 +34,7 @@ The site's structure is not too complicated. We'll be using CSS Grid to style an
-
-
+
```
@@ -236,11 +235,10 @@ function startup() {
let observerOptions = {
root: null,
rootMargin: "0px",
- threshold: [0.0, 0.75]
+ threshold: [0.0, 0.75],
};
- adObserver = new IntersectionObserver(intersectionCallback,
- observerOptions);
+ adObserver = new IntersectionObserver(intersectionCallback, observerOptions);
buildContents();
refreshIntervalID = window.setInterval(handleRefreshInterval, 1000);
@@ -267,13 +265,13 @@ function handleVisibilityChange() {
if (!previouslyVisibleAds) {
previouslyVisibleAds = visibleAds;
visibleAds = [];
- previouslyVisibleAds.forEach(function(adBox) {
+ previouslyVisibleAds.forEach(function (adBox) {
updateAdTimer(adBox);
adBox.dataset.lastViewStarted = 0;
});
}
} else {
- previouslyVisibleAds.forEach(function(adBox) {
+ previouslyVisibleAds.forEach(function (adBox) {
adBox.dataset.lastViewStarted = performance.now();
});
visibleAds = previouslyVisibleAds;
@@ -294,7 +292,7 @@ Once per pass through the browser's event loop, each {{domxref("IntersectionObse
```js
function intersectionCallback(entries) {
- entries.forEach(function(entry) {
+ entries.forEach(function (entry) {
let adBox = entry.target;
if (entry.isIntersecting) {
@@ -304,7 +302,10 @@ function intersectionCallback(entries) {
}
} else {
visibleAds.delete(adBox);
- if ((entry.intersectionRatio === 0.0) && (adBox.dataset.totalViewTime >= 60000)) {
+ if (
+ entry.intersectionRatio === 0.0 &&
+ adBox.dataset.totalViewTime >= 60000
+ ) {
replaceAd(adBox);
}
}
@@ -324,7 +325,7 @@ Our interval handler, `handleRefreshInterval()`, is called about once per second
function handleRefreshInterval() {
let redrawList = [];
- visibleAds.forEach(function(adBox) {
+ visibleAds.forEach(function (adBox) {
let previousTime = adBox.dataset.totalViewTime;
updateAdTimer(adBox);
@@ -334,8 +335,8 @@ function handleRefreshInterval() {
});
if (redrawList.length) {
- window.requestAnimationFrame(function(time) {
- redrawList.forEach(function(adBox) {
+ window.requestAnimationFrame(function (time) {
+ redrawList.forEach(function (adBox) {
drawAdTimer(adBox);
});
});
@@ -361,7 +362,8 @@ function updateAdTimer(adBox) {
if (lastStarted) {
let diff = currentTime - lastStarted;
- adBox.dataset.totalViewTime = parseFloat(adBox.dataset.totalViewTime) + diff;
+ adBox.dataset.totalViewTime =
+ parseFloat(adBox.dataset.totalViewTime) + diff;
}
adBox.dataset.lastViewStarted = currentTime;
@@ -405,7 +407,8 @@ This code finds the ad's timer using its ID, `"timer"`, and computes the number
The `buildContents()` function is called by the [startup code](#setting_up) to select and insert into the document the articles and ads to be presented:
```js
-let loremIpsum = "
Lorem ipsum dolor sit amet, consectetur adipiscing" +
+let loremIpsum =
+ "
Lorem ipsum dolor sit amet, consectetur adipiscing" +
" elit. Cras at sem diam. Vestibulum venenatis massa in tincidunt" +
" egestas. Morbi eu lorem vel est sodales auctor hendrerit placerat" +
" risus. Etiam rutrum faucibus sem, vitae mattis ipsum ullamcorper" +
@@ -414,7 +417,7 @@ let loremIpsum = "
Lorem ipsum dolor sit amet, consectetur adipiscing" +
" cursus nunc.
";
function buildContents() {
- for (let i=0; i<5; i++) {
+ for (let i = 0; i < 5; i++) {
contentBox.appendChild(createArticle(loremIpsum));
if (!(i % 2)) {
@@ -445,7 +448,7 @@ function createArticle(contents) {
articleElem.appendChild(titleElem);
articleElem.innerHTML += contents;
- nextArticleID +=1 ;
+ nextArticleID += 1;
return articleElem;
}
@@ -463,27 +466,27 @@ function loadRandomAd(replaceBox) {
{
bgcolor: "#cec",
title: "Eat Green Beans",
- body: "Make your mother proud—they're good for you!"
+ body: "Make your mother proud—they're good for you!",
},
{
bgcolor: "aquamarine",
title: "MillionsOfFreeBooks.whatever",
- body: "Read classic literature online free!"
+ body: "Read classic literature online free!",
},
{
bgcolor: "lightgrey",
title: "3.14 Shades of Gray: A novel",
- body: "Love really does make the world go round..."
+ body: "Love really does make the world go round...",
},
{
bgcolor: "#fee",
title: "Flexbox Florist",
- body: "When life's layout gets complicated, send flowers."
- }
+ body: "When life's layout gets complicated, send flowers.",
+ },
];
let adBox, title, body, timerElem;
- let ad = ads[Math.floor(Math.random()*ads.length)];
+ let ad = ads[Math.floor(Math.random() * ads.length)];
if (replaceBox) {
adObserver.unobserve(replaceBox);
@@ -512,7 +515,7 @@ function loadRandomAd(replaceBox) {
adBox.dataset.totalViewTime = 0;
adBox.dataset.lastViewStarted = 0;
- timerElem.className="timer";
+ timerElem.className = "timer";
timerElem.innerText = "0:00";
if (!replaceBox) {
@@ -560,8 +563,13 @@ function replaceAd(adBox) {
updateAdTimer(adBox);
- visibleTime = adBox.dataset.totalViewTime
- console.log(" Replacing ad: " + adBox.querySelector("h2").innerText + " - visible for " + visibleTime)
+ visibleTime = adBox.dataset.totalViewTime;
+ console.log(
+ " Replacing ad: " +
+ adBox.querySelector("h2").innerText +
+ " - visible for " +
+ visibleTime,
+ );
loadRandomAd(adBox);
}
diff --git a/files/zh-cn/web/api/intersectionobserver/index.md b/files/zh-cn/web/api/intersectionobserver/index.md
index 6e851429ea7976..2a1a151d76dfbe 100644
--- a/files/zh-cn/web/api/intersectionobserver/index.md
+++ b/files/zh-cn/web/api/intersectionobserver/index.md
@@ -43,10 +43,10 @@ const intersectionObserver = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio <= 0) return;
loadItems(10);
- console.log('Loaded new items');
+ console.log("Loaded new items");
});
// 开始监听
-intersectionObserver.observe(document.querySelector('.scrollerFooter'));
+intersectionObserver.observe(document.querySelector(".scrollerFooter"));
```
## 规范
diff --git a/files/zh-cn/web/api/intersectionobserver/observe/index.md b/files/zh-cn/web/api/intersectionobserver/observe/index.md
index d0d33eb537c5ed..08de98a499fd51 100644
--- a/files/zh-cn/web/api/intersectionobserver/observe/index.md
+++ b/files/zh-cn/web/api/intersectionobserver/observe/index.md
@@ -29,24 +29,24 @@ IntersectionObserver.observe(targetElement);
```js
// Register IntersectionObserver
-const io = new IntersectionObserver(entries => {
- entries.forEach(entry => {
+const io = new IntersectionObserver((entries) => {
+ entries.forEach((entry) => {
// Add 'active' class if observation target is inside viewport
if (entry.intersectionRatio > 0) {
- entry.target.classList.add('active');
+ entry.target.classList.add("active");
}
// Remove 'active' class otherwise
else {
- entry.target.classList.remove('active');
+ entry.target.classList.remove("active");
}
- })
-})
+ });
+});
// Declares what to observe, and observes its properties.
-const boxElList = document.querySelectorAll('.box');
+const boxElList = document.querySelectorAll(".box");
boxElList.forEach((el) => {
- io.observe(el);
-})
+ io.observe(el);
+});
```
## 规范
diff --git a/files/zh-cn/web/api/keyboard/index.md b/files/zh-cn/web/api/keyboard/index.md
index 8319dd02032b82..b4f2f325db758d 100644
--- a/files/zh-cn/web/api/keyboard/index.md
+++ b/files/zh-cn/web/api/keyboard/index.md
@@ -29,10 +29,9 @@ The following example demonstrates how to get the location- or layout-specific s
```js
if (navigator.keyboard) {
var keyboard = navigator.keyboard;
- keyboard.getLayoutMap()
- .then(keyboardLayoutMap => {
- var upKey = keyboardLayoutMap.get('KeyW');
- window.alert('Press ' + upKey + ' to move up.');
+ keyboard.getLayoutMap().then((keyboardLayoutMap) => {
+ var upKey = keyboardLayoutMap.get("KeyW");
+ window.alert("Press " + upKey + " to move up.");
});
} else {
// Do something else.