新聞中心
本文帶來5個難得一見的JavaScriot原生API,為我們的前端開發(fā)帶來意想不到的便利。

創(chuàng)新互聯(lián)專注為客戶提供全方位的互聯(lián)網(wǎng)綜合服務,包含不限于成都網(wǎng)站設計、成都網(wǎng)站制作、外貿網(wǎng)站建設、鄆城網(wǎng)絡推廣、小程序開發(fā)、鄆城網(wǎng)絡營銷、鄆城企業(yè)策劃、鄆城品牌公關、搜索引擎seo、人物專訪、企業(yè)宣傳片、企業(yè)代運營等,從售前售中售后,我們都將竭誠為您服務,您的肯定,是我們最大的嘉獎;創(chuàng)新互聯(lián)為所有大學生創(chuàng)業(yè)者提供鄆城建站搭建服務,24小時服務熱線:028-86922220,官方網(wǎng)址:www.cdcxhl.com
1. getBoundingClientRect()
Element.getBoundingClientRect() 方法返回一個 DOMRect 對象,該對象提供有關元素大小及其相對于視口的位置的信息。
domRect = element.getBoundingClientRect();
返回左、上、右、下、x、y、寬度和高度元素的值。
例如,獲取DOM元素相對于頁面左上角的top和left定位距離的值。
const h3 = document.querySelector("h3");
const rect = h3.getBoundingClientRect();
const topElement = document.documentElement;
const positionTop = topElement.scrollTop + rect.top;
const positionLeft = topElement.scrollLeft + rect.left;
2. window.getComputedStyle()
window.getComputedStyle() 方法返回一個 CSSStyleDeclaration 對象,其類型與樣式屬性相同,其中包含元素的計算樣式。
document.defaultView.getComputedStyle(element, [pseudo-element])
// or
window.getComputedStyle(element, [pseudo-element])
它有兩個參數(shù),第一個是計算樣式的元素,第二個是偽元素;如果偽元素不存在,則傳遞 null。
例子:
3. once: true
once: true 不是 API,看起來也不像。用于屬性配置,有了它,lodash的once就不用了。
const container = document.querySelector('.container');
container?.addEventListener('click', () => {
console.log('I will only do it once !')
}, {
// After configuring once, it will be called at most once
once: true
})
4. getModifierState()
如果指定的修改鍵被按下或激活,則 getModifierState() 方法返回 true。
例如,我們可以使用它來監(jiān)聽用戶在打字時是否按下了尺寸切換鍵,然后根據(jù)情況給出適當?shù)奶崾尽?/p>
5.clipboard.readText()
clipboard,我敢肯定,是一個常用的功能。
要從剪貼板中讀取文本,請調用 navigator.clipboard.readText() 并等待返回的 Promise 進行解析。
async function getClipboardContents() {
try {
const text = await navigator.clipboard.readText();
console.log('Pasted content: ', text);
} catch (err) {
console.error('Failed to read clipboard contents: ', err);
}
}
要將文本復制到剪貼板,只需調用 writeText()。
async function copyPageUrl() {
try {
await navigator.clipboard.writeText(location.href);
console.log('Page URL copied to clipboard');
} catch (err) {
console.error('Failed to copy: ', err);
}
}
總結
以上就是我今天想與你分享的5個關于JavaScript原生的API的知識內容,希望這些內容對你有所幫助。
網(wǎng)頁標題:五個罕見的JavaScript原生API
文章地址:http://m.fisionsoft.com.cn/article/cogsepe.html


咨詢
建站咨詢
