今天學到了系列第1季(HTML/JavScript/CSS 知識點)

從 2019 年 10 月底開始,我堅持每一個工做日發佈一篇題爲「今天我學到了」的沸點。就這樣點滴積累,到如今已經攢夠足夠的量,因此集結拿出來與你們共同分享。javascript

當初之因此作這樣一件事情,一方面是督促本身每日堅持學習;另外一方面,我發現有時候學到的知識點比較瑣粹,一句話就能講完,但又不夠一篇文章的體量,又得找個地方記錄下來,不然事後可能又會忘記。我發現沸點是個不錯的地方,因而就開始個人分享之旅。css

在分享的過程當中,會有一些「你說的這個問題不是什麼新鮮事了」、「你才知道嗎……」、「...毫無心義」 之類的聲音,其實我並不太在意。將這些話列出來也沒有也別的意思,只是想說:我發佈的這些沸點,對我來講確定是有用的,是讓我學到的,若是你已經知道了,那我祝賀你;若是你還不知道,但願在我學到後,也能讓你也學到,你們一塊兒點滴進步。html

好了,再多說都是廢話了。下面開始正文:java

JavaScript

1. str.replace 方法

'2019.12.13'.replace('.', '-') 的結果是 "2019-12.13",默認只替換第一個匹配的 .,若是須要替換全部的 .,就要用到正則表達式的全局標記 g 了。git

2. Array.from 方法的映射功能

Array.from() 方法將可迭代對象轉爲數組的同時,還能夠作映射(map)操做。es6

3. 使用科學計數法顯示的數字範圍

JavaScript 中如下四個區間範圍的數字會使用科學計數法顯示:github

  1. (-∞, -1e+21]
  2. [-1e-7, 0)
  3. (0, 1e-7]
  4. [1e+21, +∞)

4. Symbol.toStringTag

Object.prototype.toString() 能夠用來檢查對象類型。web

var toString = Object.prototype.toString;
toString.call('foo');     // "[object String]"
toString.call([1, 2]);    // "[object Array]"
toString.call(3);         // "[object Number]"
toString.call(true);      // "[object Boolean]"
toString.call(undefined); // "[object Undefined]"
toString.call(null);      // "[object Null]"
複製代碼

從 ES2015 開始,可使用內置的 Symbol.toStringTag,自定義對象返回的類型值。正則表達式

let Obj = {
  get [Symbol.toStringTag]() { return 'Wow' }
}
Object.prototype.toString.call(obj) // "[object Wow]"
複製代碼

你可能不知道的是,有些內置對象已經在使用 Symbol.toStringTag 定義本身的類型了。npm

Object.prototype.toString.call(new Map());       // "[object Map]"
Object.prototype.toString.call(function* () {}); // "[object GeneratorFunction]"
Object.prototype.toString.call(Promise.resolve()); // "[object Promise]"
複製代碼

參考連接:developer.mozilla.org/en-US/docs/…

5. location 對象的屬性說明

6. export default 命令的本質

JavaScript 的 export default 命令本質上是向外輸出了一個叫 default 的變量。

// module.js
const apple = '🍏', banana = '🍌'
export default apple
export { banana }
// import.js
import apple, { banana } from 'm.js'

// 等同於

// module.js
const apple = '🍏', banana = '🍌'
export {
    apple as default,
    banana
}
// import.js
import { default as apple, banana } from 'm.js'
複製代碼

就是說:

  • export default xxexport { xx as default } 的另外一種寫法
  • import xximport { default as xx } 的另外一種寫法

7. 模板字符串的另外一種用法

模板字符串(``)除了提供經常使用的插值語法(${})外,還有一個用法,這個用法爲函數提供了一種特殊調用形式 func`x`。

簡單地講:alert`123` 等同於 alert(123)

而當其中包含變量時,該模板字符串會被拆解成多個參數,再調用函數:

let a = 5;
let b = 10;

tag`Hello ${ a + b } world ${ a * b }`;
// 等同於
tag(['Hello ', ' world ', ''], 15, 50);
複製代碼

即實際調用的參數爲:

  1. 第一個參數,是「模板字符串排除變量部分」後,其他各部分字符串組成的數組。
  2. 從第二個參數開始,則由「模板字符串中的變量」組成的列表。

參考連接:es6.ruanyifeng.com/#docs/strin…"

8. 用 Array.from 處理包含 emoji 的字符串

字符串的 .length 屬性或 .charAt() 方法對像 😃 這樣的 Unicode 碼點大於 0xFFFF 的字符檢查是錯誤的。咱們可使用 ES6 引入的 Array.from 方法處理,能獲得正確結果。

const str = '😎'

// .length 屬性或 .charAt() 方法對 Unicode 碼點大於 0xFFFF 的字符檢查是錯誤的
str.charAt(0) // "�"
str.length // 2

// 使用 ES6 引入的 Array.from 方法處理,能獲得正確結果
function charAt(str, index) {
  return Array.from(str)[index] || ''
}
function strLength(str) {
  return Array.from(str).length
}
charAt('😎', 0) // "😎"
strLength('😎') // 1
複製代碼

9. 統計字符串的字節長度

JavaScript 可使用如下兩種方式,統計一個字符串佔據的字節長度:

  • new TextEncoder().encode('👀⛰️').byteLength // 10,或者
  • new Blob(['👀⛰️']).size // 10

10. 引入 Lodash ES 模塊構建

著名的 JS 工具庫 Lodash 提供了使用 ES 模塊語法引入的構建——lodash-es。所以咱們還能這樣使用它:

<script type="module"> import { uniq } from 'https://cdn.jsdelivr.net/npm/lodash-es@4.17.15/lodash.min.js' uniq([1,1,2]) // [1,2] </script>
複製代碼

11. Fullscreen API

全屏(Fullscreen) API 的簡單使用:

  • 開啓全屏:elem.requestFullscreen()
  • 退出全屏:document.exitFullscreen()

demo 地址:codepen.io/zhangbao/pe…

12. 網頁順滑滾動的原生方案

實現網頁順滑滾動(smooth scroll)的原生方式有四種:

  1. html { scroll-behavior: smooth; }
  2. window.scroll({ behavior: 'smooth' })
  3. window.scrollBy({ behavior: 'smooth' })
  4. elem.scrollIntoView({ behavior: 'smooth' })

demo 地址:codepen.io/zhangbao/pe…

13. 原型鏈繼承說明

JavaScript 中的原型鏈繼承:

  • 使用構造函數 Animal 生成的的實例對象(new Animal()),其內部的 [[Prototype]] 鏈(即 __proto__ 屬性)指向 Animal.prototype
  • ES6 類繼承語法 class Rabbit extends Animal { ... } 實際作了兩件事:Rabbit.prototype 內部的 [[Prototype]] 鏈指向 Animal.prototype,同時 Rabbit 內部的 [[Prototype]] 鏈指向 Animal

繼承細節見下圖。

14. 派發自定義事件

使用 new CustomEvent()target.dispatchEvent(event) API 就能實現 DOM 元素上的自定義事件派發。

function fireEvent(name, target, detail) {
  const event = new CustomEvent(name, {
    bubbles: true,
    detail,
  });
  target.dispatchEvent(event);
};
複製代碼

demo 地址:codepen.io/zhangbao/pe…

15. 整數與不一樣進制間的轉換

咱們可使用 numObj.toString(radix) 方法將整數轉爲不一樣進制的字符串;同時,可使用 parseInt(string, radix) 將不一樣進制的字符串轉爲十進制數字。

16. 在整數上調用方法會報錯

JavaScript 中直接在整數上調用方法,會報錯

1.toString() // Uncaught SyntaxError: Invalid or unexpected token
複製代碼

這是把調用方法時使用的點當成小數點了,避免報錯發生的方式有三種:

  1. String 函數顯式轉爲字符串
  2. 數字與點之間空一格
  3. 數字後連續兩個點
  4. 用圓括號包圍數字

17. 複製文本

使用 JavaScript 複製文本分三步:

  1. 選擇文本(input.select()
  2. 複製文本(document.execCommand('copy')
  3. 移除文本選擇(window.getSelection().removeAllRanges()

demo 地址:codepen.io/zhangbao/pe…

18. 檢查空對象

JavaScript 中檢查空對象的兩種方式:

19. 輸入框文本全選

實現輸入框文本全選功能,有兩個API可供選擇:

  1. HTMLInputElement.select()
  2. HTMLInputElement.setSelectionRange()
<input onClick="this.select();" value="via select()" />
<input onClick="this.setSelectionRange(0, this.value.length)" value="via setSelectionRange()" />
複製代碼

demo 地址:codepen.io/zhangbao/pe…

20. 一個解構賦值知識點

你可能不知道的解構賦值知識點:

  • 擴展運算符的解構賦值,只能複製目標對象的自身屬性
  • 單純的解構賦值,能夠複製目標對象繼承的屬性

21. URLSearchParams API

URLSearchParams API 能夠用來操做瀏覽器地址欄裏的 url 參數。

以 "example.com/?q=URLUtils…" 爲例。先來初始化下:

var searchParams = new URLSearchParams(location.search)
複製代碼

再來操做:

  • 獲取參數:searchParams.get('topic') // 'api'
  • 添加/更新參數:searchParams.set('topic', 'More webdev')
  • 當前參數:searchParams.toString() // "q=URLUtils.searchParams&topic=More+webdev"
  • 刪除參數:searchParams.delete('topic')
  • 是否包含參數:searchParams.has('topic') // false
  • searchParams.toString() // "q=URLUtils.searchParams"

參考連接:developer.mozilla.org/en-US/docs/…

CSS

22. 響應式字體設置

可使用 vw@media 查詢實現網站字體尺寸的響應式設置。

html {
    font-size: 1.6666666666666667vw;
}

@media (max-width: 600px) {
    html {
        font-size: 14px;
    }
}

@media (max-width: 400px) {
    html {
        font-size: 17px;
    }
}
複製代碼

23. attr() 功能函數

咱們能夠在僞元素(好比 ::after)的 content 屬性裏使用 attr() 函數獲取元素屬性值,並且還支持使用空格作字符串鏈接。

demo 連接:codepen.io/zhangbao/pe…

24. background-clip 幹什麼的?

CSS background-clip 用於限定只讓在哪一個區域的背景可見。可取值包括:border-boxpadding-boxcontent-box 和有趣的 text。

取值 padding-box,表示只讓在 padding box 區域內的背景可見,border-box(默認值)和 content-box 做用相似;當取值 text 時(就比較有趣了),表示只在文本區域內的背景是可見,或者說「文本被背景填充了」,不過須要把文本顏色設置成透明的(transparent)才能看到效果。

demo 地址:codepen.io/zhangbao/fu…

25. auto-fitauto-fill 的區別

Grid 佈局中 auto-fitauto-fill 關鍵字的區別。

  • 1fr 狀況:auto-fill 會盡量多的,在可用空間內分配更多 grid item 坑位;auto-fit 則儘量拉伸當前的 grid item ,以便填充可用空間。
  • 固寬狀況:auto-fill 在空間充裕的狀況下會分配額外的 grid item 坑位;auto-fit 則不會。

demo 地址:codepen.io/zhangbao/pe…

26. 百分比 padding 的計算依據

CSS 百分比 padding 是依據父元素的 width 計算的。以下圖所示,Child 的 padding-top: 25%,最終解析爲 400 * 0.25,也就是 100px

demo 地址:codepen.io/zhangbao/pe…

27. text-decoration-skip-ink

CSS text-decoration-skip-ink 屬性用於設置,下劃線通過字符突出的上/下邊緣時,是自動跳過仍是直接穿過。

28. text-decoration-style

text-decoration-style 有 5 個可能的取值:soliddoubledotteddashedwavy。渲染結果以下:

demo 地址:codepen.io/zhangbao/pe…

29. 使用 scaleX(-1)/scaleY(-1) 實現翻轉功能

使用 scaleX(-1)/scaleY(-1) 實現元素在 X軸/Y軸 方向上的翻轉。

demo 地址:codepen.io/zhangbao/pe…

30. :placeholder-shown

:placeholder-shown<input><textarea>placeholder 屬性有關。當輸入框中的佔位文本顯示時,就匹配這個輸入框。有幾個邊緣狀況,須要注意:

demo 地址:codepen.io/zhangbao/pe…

31. 邏輯屬性:inline-size、block-size

inline-sizeblock-size 屬性的含義與網頁的書寫模式(writing-mode)有關。以文字排版爲例:

  • 文字書寫的方向稱爲 x/inline 軸,元素在這個軸上佔據的尺寸稱爲 inline size。
  • 文字折行的方向稱爲 y/block 軸,元素在這個軸上佔據的尺寸稱爲 block size。

所以這兩個屬性跟 widthheight 存在某種對應關係:

  • 在默認書寫模式(writing-mode: horizontal-tb;)下,width = inline-size,height = block-size
  • 而在垂直書寫模式下(好比 writing-mode: vertical-rl;)下,width = block-size,height = inline-size

demo 地址:codepen.io/zhangbao/pe…

32. clip-path

使用 clip-path 屬性裁剪元素的兩種方式:

demo 地址:codepen.io/zhangbao/fu…

33. :nth-child 與 :nth-of-type 的區別

:nth-child(1):nth-of-type(1) 的區別:

span:nth-child(1) 匹配的是:1. <span>;2. 是父元素的第一個孩子。判斷條件使用 JS 表達是下面這樣的:

if (parent.children[0] && parent.children[0].tagName === 'SPAN') {
    /* 爲元素應用樣式... */
}
複製代碼

a:nth-of-type(1) 匹配的是:在父元素範圍內第一個出現的 <a>,查找邏輯使用 JS 表達是下面這樣的:

if (document.querySelectorAll('.nav > a')[0]) {
    /* 爲元素應用樣式... */
}
複製代碼

demo 地址:codepen.io/zhangbao/pe…

34. Flex 項目的內容尺寸 & 基礎尺寸

Flex 項目的最終渲染尺寸是基於內容尺寸/基礎尺寸進行的:

  • 當 Flex 項目設置了 flex-basiswidth(同時設置時,flex-basis 優先級高於 width)時,它是基於此基礎尺寸縮減/增加的。
  • 當 Flex 項目未設置 flex-basiswidth 時,則是基於內容尺寸(max-content)縮減/增加的。

demo 地址(Firefox 中打開觀察):codepen.io/zhangbao/fu…

35. 區分鼠標聚焦和 Tab 鍵索引聚焦

:focus-visible 僞類能夠區分一個元素是經過鼠標點擊聚焦的,仍是經過 Tab 鍵索引聚焦的。

這樣就能實現如下的交互效果——點擊 <button> 時不會出現 outline,而用 Tab 鍵索引時出現 outline。

demo 地址:codepen.io/zhangbao/pe…

36. writing-mode

在不一樣的 writing-mode 取值下,文字排版(文檔流)方向的表現:

demo 地址:codepen.io/zhangbao/fu…

37. Grid 項目最終渲染尺寸

使用了 grid-template-columns: 1fr 1fr 以後,就能保證兩個 Grid 項目同樣寬嗎?不必定。

若是一個 Grid 項目的 min-content 大於最終計算出來的 1fr 的值,那麼這個 Grid 項目最終渲染尺寸是 min-content

demo 地址:codepen.io/zhangbao/fu…

38. visibility 屬性

CSS 的 visibility 屬性有一個有趣的地方——父元素 visibility: hidden,子元素 visibility: visible,最終的呈現效果是:父元素不可見,這個子元素倒是可見的。

demo 地址:codepen.io/zhangbao/fu…

39. text-decoration 是個複合屬性

CSS 中的 text-decoration 是個複合屬性,語法以下:

text-decoration: <'text-decoration-line'> || <'text-decoration-style'> || <'text-decoration-color'>

其中每一個單獨屬性的初始值以下:

  • text-decoration-line: none
  • text-decoration-style: solid
  • text-decoration-color: currentcolor

就是說,當咱們使用 text-decoration: underline 的時候,實際做用的是 text-decoration: underline solid currentcolor

連接:developer.mozilla.org/en-US/docs/…

HTML

40. rel="nofollow"

某些我的網站上會出現一些垃圾評論外鏈,有些外鏈的目的是爲了提升本身網站的搜索引擎排名。

爲了告知搜索引擎此外鏈不被網站信任,無需計入搜索排名。能夠這樣作:

<a rel="nofollow" target="_blank">
複製代碼

更進一步,添加避免本頁面被外鏈網頁操做的代碼:

<a rel="nofollow noopener noreferrer" target="_blank">
複製代碼

參考連接:ahrefs.com/blog/zh/nof…

41. rel="noopener noreferrer"

在當前頁面使用 <a target="_blank">window.open() 打開新頁面時,若是不作特殊處理,在新頁面中可使用 window.opener 訪問當前頁面的 window 對象。

後果是在新頁面中可以重置當前頁面的 url 地址:window.opener.location = 'evil.com'

爲了不這類事情發生,咱們可使用下圖的作法。

參考連接:mathiasbynens.github.io/rel-noopene…

(完)

相關文章
相關標籤/搜索