<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Ivy Ho on Medium]]></title>
        <description><![CDATA[Stories by Ivy Ho on Medium]]></description>
        <link>https://medium.com/@ivycodefive?source=rss-3691ce586f53------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*GUtB3Gje2AgGe3P0-qsbNw.jpeg</url>
            <title>Stories by Ivy Ho on Medium</title>
            <link>https://medium.com/@ivycodefive?source=rss-3691ce586f53------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 11:18:11 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ivycodefive/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[[筆記] Vue3 watch 用法 — 4 種數據、5 種情境]]></title>
            <link>https://medium.com/ivycodefive/%E7%AD%86%E8%A8%98-vue3-watch-%E7%94%A8%E6%B3%95-4-%E7%A8%AE%E6%95%B8%E6%93%9A-5-%E7%A8%AE%E6%83%85%E5%A2%83-ec9ad4995049?source=rss-3691ce586f53------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec9ad4995049</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[vue-3]]></category>
            <category><![CDATA[vue]]></category>
            <category><![CDATA[vuejs]]></category>
            <dc:creator><![CDATA[Ivy Ho]]></dc:creator>
            <pubDate>Wed, 24 Jan 2024 14:42:54 GMT</pubDate>
            <atom:updated>2024-01-25T14:28:40.750Z</atom:updated>
            <content:encoded><![CDATA[<h3>[筆記] Vue3 watch 用法 — 4 種數據、5 種情境</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*n3Pl1k5C0ZX_FOBk" /><figcaption>Photo by <a href="https://unsplash.com/@plhnk?utm_source=medium&amp;utm_medium=referral">Paul Hanaoka</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Vue3 watch 可監視的數據分為以下 4 種 :</h3><ol><li>ref 定義的數據(包括計算屬性)</li><li>reactive 定義的數據</li><li>getter 函數(函數返回一個值)</li><li>一個包含上述內容的陣列</li></ol><p>(參考 <a href="https://cn.vuejs.org/guide/essentials/watchers.html#watch-source-types">官方文檔內容</a>)</p><h3><strong>分別用以下 5 種情境進行說明:</strong></h3><ul><li>情況一、監視 ref定義的基本類型數據</li><li>情況二、監視 ref 定義的物件類型數據</li><li>情況三、監視 reactive定義的物件類型數據 <em>(reactive 無法定義基本類型數據)</em></li><li>情況四、監視 ref或reactive定義的物件類型數據中的某個屬性</li><li>情况五、監視上述的多個數據</li></ul><h4>情況一、監視 ref 定義的基本類型數據</h4><blockquote>用法 : <strong>watch(要監視的對象, 回呼函式)</strong></blockquote><ul><li>要監視的對象直接寫數據名即可 (不需要加.value )</li></ul><pre>const sum = ref(0)<br><br>watch(sum,(newValue, oldValue) =&gt; {<br>  console.log(&#39;sum 改變了&#39;, newValue, oldValue)<br>})</pre><ul><li>可用以下方式解除 watch</li></ul><pre>const sum = ref(0)<br><br>const stopWatch = watch(sum, (newValue, oldValue)=&gt;{<br>  console.log(&#39;sum 改變了&#39;, newValue, oldValue)<br><br>  if(newValue &gt;= 10) {<br>    stopWatch()<br>  }<br>})</pre><h4>情況二、監視 ref 定義的物件類型數據</h4><p><strong>1 . 監聽對象直接寫數據名</strong></p><pre>const person = ref({<br>  name: &#39;Taylor&#39;,<br>  age: 20<br>})<br><br>watch(person, (newValue, oldValue) =&gt; {<br>  console.log(&#39;person 改變了&#39;, newValue, oldValue)<br>})</pre><ul><li>監視的是物件的<strong>地址值</strong>，當 person 物件的地址值改變，才會觸發。</li><li>當物件地址值改變，能夠成功取得不同的 newValue 和 oldValue。</li><li>以下範例，只有按下&quot;換掉整個人&quot; ，watch 才會監測到 :</li></ul><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;p&gt;姓名 : {{ person.name }}&lt;/p&gt;<br>    &lt;p&gt;年齡 : {{ person.age }}&lt;/p&gt;<br><br>    &lt;button @click=&quot;changeName&quot;&gt;修改姓名&lt;/button&gt;<br>    &lt;button @click=&quot;changeAge&quot;&gt;修改年齡&lt;/button&gt;<br>    &lt;button @click=&quot;changePerson&quot;&gt;換掉整個人&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import { ref, watch } from &#39;vue&#39;<br><br>const person = ref({<br>  name: &#39;Taylor&#39;,<br>  age: 20<br>})<br><br>const changeName = () =&gt; {<br>  person.value.name += &#39;~&#39;<br>}<br><br>const changeAge = () =&gt; {<br>  person.value.age += 10<br>}<br><br>const changePerson = () =&gt; {<br>  person.value = {<br>    name: &#39;Ari&#39;,<br>    age: 18<br>  }<br>}<br><br>watch(person, (newValue, oldValue) =&gt; {<br>  console.log(&#39;person 改變了&#39;, newValue, oldValue)<br>})<br>&lt;/script&gt;</pre><p><strong>2 . 如果希望當物件內任一屬性改變，都會觸發 watch 回呼函式，需手動開啟深度監視 </strong><strong>{ deep:true }</strong></p><pre>watch(<br>  person,<br>  (newValue, oldValue) =&gt; {<br>    console.log(&#39;person 改變了&#39;, newValue, oldValue)<br>  },<br>  { deep: true }<br>)</pre><ul><li>加上 { deep: true } 之後，無論換掉物件內的屬性，還是一整個物件重新賦值，watch 都能監測到，並且觸發回呼函式。</li></ul><p><strong>需要注意的問題</strong></p><p>此時按下 “修改姓名” 和 “修改年齡” 雖然能夠觸發 watch，但 <strong>newValue 與</strong> <strong>oldValue 抓到的物件內容是相同的，皆會顯示修改後的數據。</strong></p><p><strong>補充: </strong><strong>{ immediate: true }</strong></p><ul><li>除了{ deep: true } ，還可設定其他配置項目，常見的還有將 immediate 設為 true，在頁面初始就會先執行一次 watch 的回呼函式。</li></ul><pre>watch(person, (newValue, oldValue) =&gt; {<br>  console.log(&#39;person 改變了&#39;, newValue, oldValue)<br>},{ deep: true, immediate: true })</pre><h4>情況三、監視 reactive 定義的物件類型數據</h4><ul><li>直接監聽數據名，<em>默認開啟深度監視，</em>不須加上{ deep: true }</li><li>即使加上 { deep: false} 也無法關閉深度監視。</li></ul><pre>const person = reactive({<br>  name: &#39;Taylor&#39;,<br>  age: 20<br>})<br><br>watch(person, (newValue, oldValue) =&gt; {<br>  console.log(&#39;person 改變了&#39;, newValue, oldValue)<br>})</pre><p>由於使用 reactive 所定義的數據，無法對其物件重新賦值，只能修改物件內的屬性，所以我們將 changePerson 改為使用 Object.assign 的方式去換掉整個人，範例修改如下 :</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;p&gt;姓名 : {{ person.name }}&lt;/p&gt;<br>    &lt;p&gt;年齡 : {{ person.age }}&lt;/p&gt;<br><br>    &lt;button @click=&quot;changeName&quot;&gt;修改姓名&lt;/button&gt;<br>    &lt;button @click=&quot;changeAge&quot;&gt;修改年齡&lt;/button&gt;<br>    &lt;button @click=&quot;changePerson&quot;&gt;換掉整個人&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import { watch, reactive } from &#39;vue&#39;<br><br>const person = reactive({<br>  name: &#39;Taylor&#39;,<br>  age: 20<br>})<br><br>const changeName = () =&gt; {<br>  person.name += &#39;~&#39;<br>}<br><br>const changeAge = () =&gt; {<br>  person.age += 10<br>}<br><br>const changePerson = () =&gt; {<br>  Object.assign(person, {<br>    name: &#39;Ari&#39;,<br>    age: 18<br>  })<br>}<br><br>watch(person, (newValue, oldValue) =&gt; {<br>  console.log(&#39;person 改變了&#39;, newValue, oldValue)<br>})<br>&lt;/script&gt;</pre><p><strong>需要注意的問題</strong></p><p>此時按下 “修改姓名” 和 “修改年齡” 甚至 “修改整個人”，<strong>oldValue 與 newValue 抓到的仍然是相同內容的物件，皆顯示修改後的數據。</strong></p><blockquote>為什麼 ref 所定義的物件，在按下 “修改整個人” 可以抓到不同的新舊值，改為用 reactive 定義物件卻不行?</blockquote><p>使用 ref 定義物件類型數據，我們可以使用 person.value 來對其重新賦值。剛剛提到，由於 reactive 的使用方法是預設無法對其定義的物件重新賦值的，只能修改物件內的屬性，在 changePerson 我們使用 Object.assign來替換掉物件內的屬性，實質上地址值是沒有改變的。</p><h4>情況四、監視 ref 或 reactive 定義的物件類型數據中的某個屬性</h4><ol><li><strong>監視(由 ref 或 reactive 定義的)響應式物件中的某個屬性，且該屬性為基本類型</strong></li></ol><ul><li>當我們只想在 person 物件內的 name 屬性產生變化時，才觸發 watch 回呼函式</li><li>寫法需要將監聽的對象寫成一個 getter 函數 (一個函數返回一個值)</li><li>監聽的對象也就變成 ()=&gt; { return person.value.name } (以 ref 為例)</li><li>可簡寫為 ()=&gt; person.value.name</li></ul><pre>watch(<br>  () =&gt; person.value.name,<br>  (newValue, oldValue) =&gt; {<br>    console.log(&#39;person 內的 name 改變了&#39;, newValue, oldValue)<br>  }<br>)</pre><ul><li>此時監視的對象很具體指明為 person.value.name，在這種方法下， newValue 和 oldValue 也能成功抓到不同的新舊值。</li></ul><p><strong>2. 監視(由 ref 或 reactive 定義的)響應式物件中的某個屬性，且該屬性為物件類型</strong></p><p>將範例中 person 數據內新增第二層 albums 物件 (以 ref 為例):</p><pre>&lt;template&gt;<br>  &lt;div&gt;<br>    &lt;p&gt;姓名 : {{ person.name }}&lt;/p&gt;<br>    &lt;p&gt;年齡 : {{ person.age }}&lt;/p&gt;<br>    &lt;p&gt;作品 : {{ person.albums.album1 }} , {{ person.albums.album2 }}&lt;/p&gt;<br><br>    &lt;button @click=&quot;changeAlbum1&quot;&gt;換掉專輯一&lt;/button&gt;<br>    &lt;button @click=&quot;changeAlbum2&quot;&gt;換掉專輯二&lt;/button&gt;<br>    &lt;button @click=&quot;changeAlbums&quot;&gt;換掉全部專輯&lt;/button&gt;<br>  &lt;/div&gt;<br>&lt;/template&gt;<br><br>&lt;script setup&gt;<br>import { ref, watch } from &#39;vue&#39;<br><br>const person = ref({<br>  name: &#39;Taylor&#39;,<br>  age: 20,<br>  albums: {<br>    album1: &#39;folklore&#39;,<br>    album2: &#39;evermore&#39;<br>  }<br>})<br><br>const changeAlbum1 = () =&gt; {<br>  person.value.albums.album1 = &#39;Positions&#39;<br>}<br><br>const changeAlbum2 = () =&gt; {<br>  person.value.albums.album2 = &#39;Eternal Sunshine&#39;<br>}<br>const changeAlbums = () =&gt; {<br>   person.value.albums = { album1: &#39;Heard It in a Past Life&#39;, album2: &#39;Surrender&#39; }<br>}<br>&lt;/script&gt;</pre><p><strong>當我們想要監視 person 內的 albums 物件</strong></p><ul><li>建議要將監聽對象寫成一個 getter 函數 (一個函數返回一個值)</li><li>監聽的是 albums 物件的地址值</li><li>此時只有按下 &quot;換掉全部專輯&quot;，才會觸發 watch</li><li>可成功取得不同的新舊值</li></ul><pre>watch(<br>  () =&gt; person.value.albums,<br>  (newValue, oldValue) =&gt; {<br>    console.log(&#39;person.value.albums 改變了&#39;, newValue, oldValue)<br>  }<br>)</pre><p><strong>當我們希望在 albums 內屬性變化時，也觸發 watch</strong></p><ul><li>需要再手動開啟深度監視 { deep: true }</li><li>此時按下 “換掉專輯一”、“換掉專輯二”、“換掉全部專輯” 皆會觸發 watch</li><li>但只有按下 “換掉全部專輯” 時能成功取得不同的新舊值，前兩者無法取得不同的新舊值。</li></ul><pre>watch(<br>  () =&gt; person.value.albums,<br>  (newValue, oldValue) =&gt; {<br>    console.log(&#39;person.value.albums 改變了&#39;, newValue, oldValue)<br>  },<br>  { deep: true }<br>)</pre><h4><strong>情况五、監視上述的多個數據</strong></h4><ul><li>用法是將多個數據使用陣列包起來</li><li>其實就是延續情況一 ~ 情況四的那些監聽方法，並且需要監聽什麼就放進陣列裡。</li><li>例如我們希望監視 person 中的 name 屬性以及 albums 物件，且希望在 albums 內的屬性有變動時也能觸發 watch :</li></ul><pre>watch(<br>  [() =&gt; person.value.name, () =&gt; person.value.albums],<br>  (newValue, oldValue) =&gt; {<br>    console.log(&#39;person albums 改變了&#39;, newValue, oldValue)<br>  },<br>  { deep: true }<br>)</pre><ul><li>newValue 和 oldValue 抓到的會是一整個陣列 (是否能成功取得不同的新舊值，參考情況一~情況四)</li><li>不同數據改變，都會觸發同一個回呼函式，如果不希望如此，將他們分開監視是比較好的做法。</li></ul><h4>重點回顧</h4><ul><li>用 ref 定義的基本類型數據，作為監視對象，名稱不須加上 .value 。</li><li>用 reactive 定義的物件類型數據，作為監視對象，預設開啟深度監視，不須額外設定 { deep: true } 來監視(只有一層)物件型別內的任一屬是否性產生變化。</li></ul><p>為了方便對照，我將此篇內容整理成以下表格 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gzl5y6XbeIvQR5RRR0VzuQ.png" /></figure><h4>參考資料</h4><p><a href="https://www.youtube.com/watch?v=c2ZaqEyLVZI&amp;list=PLmOn9nNkQxJEnGM4Jf0liBcyedAtuQq-O&amp;index=18">【极简Vue3】017 watch监视 情况一 (youtube.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec9ad4995049" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ivycodefive/%E7%AD%86%E8%A8%98-vue3-watch-%E7%94%A8%E6%B3%95-4-%E7%A8%AE%E6%95%B8%E6%93%9A-5-%E7%A8%AE%E6%83%85%E5%A2%83-ec9ad4995049">[筆記] Vue3 watch 用法 — 4 種數據、5 種情境</a> was originally published in <a href="https://medium.com/ivycodefive">IvyCodeFive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[LidemyOJ 學習筆記 - [#1008-幾個水桶]]]></title>
            <link>https://medium.com/ivycodefive/lidemyoj-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-1008-%E5%B9%BE%E5%80%8B%E6%B0%B4%E6%A1%B6-ca976b681b75?source=rss-3691ce586f53------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca976b681b75</guid>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ivy Ho]]></dc:creator>
            <pubDate>Tue, 22 Aug 2023 03:30:04 GMT</pubDate>
            <atom:updated>2023-08-22T03:30:04.454Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vTOTJTyElqPIYCOk" /><figcaption>Photo by <a href="https://unsplash.com/@punkidu?utm_source=medium&amp;utm_medium=referral">Ella Ivanescu</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>最近在看 Huli 大大的「先別急著寫 leetcode 」課程練功，做到一題有趣的題目，想來寫寫文章做個筆記。</p><h3>題目</h3><p>故事有點長，以下用白話文簡述 :</p><p>很久很久以前，有個 Lidemy 王國，這個王國的每個水桶容量都是 2 的 n 次方，例如最小的五個水桶的容量為：</p><p>1、2、4、8、16</p><p>而最大的水桶容量為 2³¹ = 2147483648。</p><p>國王派士兵去取水，希望每一次取水都能帶<strong>最少的水桶</strong>去，而且<strong>每一個水桶一定都要裝滿。</strong></p><p>現在已知要取水的單位(input)，請幫忙算算看，最少需要帶幾個水桶(output)?</p><p>參考以下範例 :</p><p>input : 20</p><p>output : 2</p><p>Hint : 20 單位的水，帶一個 16 的水桶加一個 4 的水桶即可，所以答案是 2</p><h3>我的解法</h3><h4>初步解題想法</h4><ol><li>找出 &lt; = 總水量的最大水桶容量</li><li>算出剩餘還沒裝的水量</li><li>剩下的水再重複 1 、2 步驟，每找一次，水桶數就加 1 ，直到剩餘水量為 0</li></ol><h4>程式碼</h4><p>想了老半天，想出以下解法 :</p><pre>  <br>function solve(lines) { <br>  let w = Number(lines[0]);  // 因 LidemyOJ 作答方式的限制，所以以這種方式取出 input<br>  let bucketNum = 0;<br>  <br>  function checkWater(w) {<br>    let bucketWater = 0;<br>    let i = 0;<br><br>    // 找出容量小於等於總水量的最大水桶<br>    while(Math.pow(2, i) &lt;= w) {<br>      bucketWater = Math.pow(2, i);<br>      i++<br>    }<br><br>    // 算出裝完還剩多少水<br>    let leftWater = w - bucketWater;<br>    return leftWater;<br>  }<br><br>  <br>  while(w != 0) { <br>    // 重複執行 checkWater 直到水量為 0<br>    w = checkWater(w);<br>    <br>    // 每執行一次，水桶數就 +1<br>    bucketNum ++ <br>  }<br><br>  console.log(bucketNum) // output<br><br>}</pre><h3>Huli 的解法</h3><p>共提供三個解法如下</p><h4>解法一</h4><ul><li>我們不會重複使用一樣容量的水桶，因為如果用一個 4 和一個 4 去裝水，不如帶一個 8 去就能解決。所以我們能從最大容量的水桶開始查找，慢慢用越來越小容量的水桶把水裝完。</li></ul><pre>function solve(lines) {<br>  let n = Number(lines[0]);<br><br> // 用 for 迴圈分別跑出所有水桶容量，並用陣列表示<br>  let arr = [];<br>  for(let i=1; i&lt;= 2**31; i*=2) {<br>    arr.push(i)<br>  }<br>  <br>  let sum = 0; // 計算水桶量<br><br>  // 使用 for 迴圈從最大容量開始倒著遍歷<br>  for(let i=arr.length - 1; i&gt;=0; i--) {<br>   <br>    // 找出容量小於等於總水量的最大水桶<br>    if(arr[i] &lt;= n) {<br>      n-= arr[i] // 算出剩餘水量<br>      sum++ // 水桶數加一<br>    }<br>  }<br><br>  console.log(sum)<br>}</pre><h4>解法二</h4><p>利用二進位的觀念解題。</p><p><strong>先剖析十進位是如何組成的</strong></p><pre>123 = 1x100 + 2x10 + 3x1<br><br>  = 1x10^2 + 2x10^1 + 3x10^0  // ^為次方符號</pre><p><strong>剖析將二進位轉換為十進位的過程</strong></p><pre>10100 = 1x2^4 + 0 + 1x2^2 + 0 + 0<br>     = 2^4 + 2^2<br>     = 20</pre><p>由過程可以發現，20 是由 2⁴ + 2² 所組成。</p><p>因此，將一個數(input) 轉換為二進位，再找出二進位的字串中有幾個 1，便是答案，也就是我們需要的水桶數量(output)!</p><p><strong>JS 數字 10 進位轉 2 進位的方法</strong></p><pre>(20).toString(2) // 10100</pre><p><strong>找出二進位的字串中有幾個 1</strong></p><ul><li>字串一樣可以用 for 迴圈查找 (每次都會忘記，還在想說要不要先把它轉成陣列)</li></ul><pre>for(let i=0; i&lt;str.length; i++) {<br> if(str[i] === &#39;1&#39;) {<br>  sum++<br> }<br>}</pre><p><strong>完整解法如下</strong></p><pre>function solve(lines) {<br>  let n = Number(lines[0])<br>  let sum = 0;<br><br>  // 將總水量轉換為二進位字串<br>  let str = n.toString(2);<br><br>  <br>  for(let i=0; i&lt;str.length; i++) {<br>    // 字串中每找到一個 &#39;1&#39;, 水桶數就 +1<br>    if(str[i] === &#39;1&#39;) {<br>      sum++<br>    }<br>  }<br><br>  console.log(sum)<br><br>}</pre><h4>解法三</h4><ul><li>解法二的延伸</li><li>利用 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Right_shift">右移運算符</a> 與 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Bitwise_AND">按位與(&amp;)運算符</a></li></ul><pre>function solve(lines) {<br>  let n = Number(lines[0])<br>  let sum = 0;<br><br>  // 跑迴圈直到水量為 0<br>  while(n&gt;0) {<br>    // n&amp;1 可以回傳 n 的 2 進位數最後一位是 0 還是 1<br>    sum += n&amp;1; <br>  <br>    // 每加完一次就往右移，也就是去掉最後一位數，繼續檢查、累加<br>    n &gt;&gt;= 1 <br>  }<br><br>  console.log(sum)<br>}</pre><p>一個問題能有許多不同的解法，一直都是學習程式的路上讓我覺得十分有趣的地方。做完題目也深刻感覺到自己相關知識方面的不足，看完解法二和解法三，簡直驚呆，尤其解法三，更是太狠了。</p><p>當初在 leetcode 的世界，總還是覺得有些寸步難行，看完題目腦袋都一片空白😵。後來發現 Huli 的這個課程，正如課程某章節的標題說到，「初學者只管拿分，誰管你什麼效率」，決定先開始當個能拿分的小菜雞再說⭐️⭐️⭐️✔️，這陣子陸續看了幾個章節後，發現在訓練程式邏輯思考方面，對我來說真的十分有幫助，也推薦給大家~</p><p><a href="https://lidemy.com/p/alg101-leetcode">[ALG101] 先別急著寫 leetcode</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca976b681b75" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ivycodefive/lidemyoj-%E5%AD%B8%E7%BF%92%E7%AD%86%E8%A8%98-1008-%E5%B9%BE%E5%80%8B%E6%B0%B4%E6%A1%B6-ca976b681b75">LidemyOJ 學習筆記 - [#1008-幾個水桶]</a> was originally published in <a href="https://medium.com/ivycodefive">IvyCodeFive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JavaScript 30]Day19-Unreal Webcam Fun]]></title>
            <link>https://medium.com/ivycodefive/javascript-30-day19-unreal-webcam-fun-fab2f2d7517a?source=rss-3691ce586f53------2</link>
            <guid isPermaLink="false">https://medium.com/p/fab2f2d7517a</guid>
            <category><![CDATA[js30]]></category>
            <category><![CDATA[前端筆記]]></category>
            <category><![CDATA[學習筆記]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ivy Ho]]></dc:creator>
            <pubDate>Sat, 08 Oct 2022 06:50:57 GMT</pubDate>
            <atom:updated>2022-10-08T06:50:57.432Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPkSYwkdClnZLStSHWTxBQ.png" /></figure><p>今天要練習利用 JavaScript 來控制 webcam 記錄影像，並使用 canvas 進行拍照(影像截圖)，以及製作濾境效果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/855/1*znMwYPrYct85zDdXg_fEug.png" /><figcaption>課程影片截圖 (Wes 大大本人)</figcaption></figure><h4>功能需求</h4><ol><li>驅動 webcam</li><li>製作拍照(影像截圖)功能</li><li>濾鏡效果</li></ol><h4>學習重點</h4><ul><li>取得鏡頭的權限: <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia">navigator.mediaDevices.getUserMedia</a></li><li>顯示影像 : <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/srcObject">video.srcObject</a> = localMediaStream; 、 <a href="https://www.w3schools.com/tags/av_met_play.asp">video.play()</a>;</li><li>將影像繪製到 Canvas 畫布上 : <br>ctx.<a href="https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/drawImage">drawImage</a>(video, 0, 0, width, height);</li><li>取得畫布上像素資訊 :<br>let pixels = ctx.<a href="https://developer.mozilla.org/zh-CN/docs/Web/API/CanvasRenderingContext2D/getImageData">getImageData</a>(0, 0, width, height);</li><li>將像素資訊設定回畫布 :<br>ctx.<a href="https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/putImageData">putImageData</a>(pixels, 0 , 0);</li><li>監聽 <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLMediaElement/canplay_event">canplay</a> 事件 : <br>video.addEventListener(&#39;canplay&#39;, paintToCanvas );</li><li>從 canvas 中取得截圖影像資訊 :<br>canvas.<a href="https://developer.mozilla.org/zh-TW/docs/Web/API/HTMLCanvasElement/toDataURL">toDataURL</a>(&#39;image/jpeg&#39;)</li><li>&lt;a&gt; 連結可加上 <a href="https://www.w3schools.com/tags/att_a_download.asp">download 屬性</a> :<br>.setAttribute(&#39;download&#39;, &#39;fileName&#39;);</li></ul><h4>觀察範例檔案初始狀態</h4><p><strong>初始畫面 :</strong></p><p>左上角有一顆拍照按鈕，</p><p>以及許多可拖曳調整的 input (將會用來控制最後的 greenScreen 效果)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*wJl4xCizXMSCy4MAYq1cvA.png" /></figure><p><strong>HTML :</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*2SL5QA08e3kFYpUfazUd1w.png" /></figure><p><strong>JS :</strong></p><p>預先取得 DOM 節點</p><pre><strong>// 原始影像的位置</strong><br>const video = document.querySelector(&#39;.player&#39;);</pre><pre><strong>// 呈現濾淨效果的位置(canvas畫布)</strong><br>const canvas = document.querySelector(&#39;.photo&#39;);<br>const ctx = canvas.getContext(&#39;2d&#39;);</pre><pre><strong>// 產生截圖照片的位置</strong><br>const strip = document.querySelector(&#39;.strip&#39;);</pre><pre><strong>// 點擊照相功能時產生的音效</strong><br>const snap = document.querySelector(&#39;.snap&#39;);</pre><p><strong>(最後完成的完整 JS 程式碼，以及檔案下載、課程連結，將放在最下方)</strong></p><h4>步驟拆解</h4><p>一、利用 JavaScript 驅動 webcam</p><p>二、將取得的影像貼到 canvas 畫布上，並製作拍照功能</p><p>三、製作濾鏡效果 :</p><ol><li>紅色特效 : redEffect</li><li>rgb 分散特效 : rgbSplit</li><li>綠幕效果 : greenScreen</li></ol><h4>一、利用 JavaScript 驅動 webcam</h4><p><strong>1. 載入套件</strong></p><p>由於我們要調用 <a href="https://developer.mozilla.org/en-US/docs/Web/API/MediaDevices/getUserMedia">getUserMedia()</a> 這個 api，以取得使用者的相機權限，需要在以下這三種安全連線的情況下使用 :</p><ol><li>https</li><li>file:///</li><li>localhost</li></ol><p>而 localhost 也是屬於安全的來源，所以範例中是利用npm來安裝 browser-sync 套件，在本地端架設 localhost server。</p><p>下載範例後，在終端機執行以下指令 :</p><pre>npm install // 安裝 package.json 內的套件<br>npm run start // 啟動 browser-sync 套件，開啟頁面。</pre><p><strong>2. 開始利用 JavaScript 驅動 webcam</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*cyHoXhVjX7zkWk2SikSctQ.png" /></figure><ul><li>利用 navigator.mediaDevices.getUserMedia({ video : true, audio : false}) 取得鏡頭權限，會返回一個 promise 物件，所以接著利用 then 、catch 來處理。</li><li>接下來影片中的寫法 :<br>video.src = window.URL.createObjectURL(localMediaStream);<br>目前 Chorme、firefox 已經不支援，改使用以下寫法 :<br>video.srcObject = localMediaStream; 將回傳的 localMediaStream 物件設為媒體來源。</li><li>透過 video.play() 來播放影片</li></ul><p>結束這個步驟後，就能在瀏覽器頁面右上方看見鏡頭所拍攝的畫面了 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*-vu6rNmeN4bnRimhP3YaUQ.png" /><figcaption>課程影片截圖</figcaption></figure><h4>二、將取得的影像貼到 canvas 畫布上，並製作拍照功能</h4><p><strong>1. 將取得的影像貼到 canvas 畫布上</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/541/1*lXCkjY-N9lnPOevJjjfuJw.png" /></figure><pre>ctx.drawImage(video, 0, 0, width, height);</pre><p>ctx.drawImage() 能將影像貼到畫布，括號中使用的參數分別是 :</p><p>video — 影像的來源</p><p>0 — 影像左上角的X座標</p><p>0 — 影像左上角的Y座標</p><p>width — 影像寬度</p><p>height — 影像高度</p><p>到這個步驟，已經能在下方 canvas 畫布中，以每 16 毫秒顯示鏡頭錄製的影像 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*a_dZLq1vj_XrAil2Igxgxw.png" /><figcaption>課程影片截圖 (後面有隻可愛的狗在睡覺，一開始以為牠是假的🥺)</figcaption></figure><p><strong>2. 製作拍照功能</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/668/1*3Tkj_ym7Q1Mvld1-oyPTRw.png" /></figure><ul><li>html 預設範例中的 .snap 是一個快門聲音效</li></ul><pre>&lt;audio class=&quot;snap&quot; src=&quot;./snap.mp3&quot; hidden&gt;&lt;/audio&gt;</pre><ul><li>canvas.toDataURL(type, encoderOptions) 可以將圖片轉成 base64，回傳含有圖像和參數設置特定格式的 data URIs (預設為 PNG，這邊將它設定為 jpeg 格式)。</li><li>每拍一張照片，就生成一個 &lt;a&gt; 連結，並將連結的 href 設定為剛剛取得的圖像 data 資訊。</li><li>同時，圖像 data 資訊也作為 &lt;img&gt; 標籤的 src 屬性值，並使用 innerHTML 塞進 &lt;a&gt; 標籤內。</li><li>html 已在按鈕綁定 takePhoto 的 click 事件 :<br>&lt;button onClick=&quot;takePhoto()&quot;&gt;Take Photo&lt;/button&gt;</li><li>.strip 即為照片顯示的區域，範例檔已預先寫好了照片連結的樣式，所以按下按鈕拍完照片後，會出現一張張照片，顯示在下方。</li><li>由於在 &lt;a&gt; 連結加入了 download 屬性，所以點擊照片連結，即可將該張 handsome.jpg下載下來。=&gt; link.setAttribute(&#39;download&#39;, &#39;handsome&#39;);</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*FqcbYvHFYJLro6Wa7T_oNA.png" /><figcaption>課程影片截圖</figcaption></figure><p><strong>三、製作濾鏡效果</strong></p><p><strong>原理 :</strong></p><p>取得畫布上的像素資訊 =&gt; 改變像素資訊 =&gt; 將像素資訊設定回畫布</p><p><strong>回到 paintToCanvas () 這個 function 內，在這邊做以上的三步驟</strong></p><pre>// 取得畫布上的像素資訊<br>let pixels = ctx.getImageData(0, 0, width, height);</pre><pre>// 改變像素資訊 (套用濾鏡效果的地方)<br>pixels = redEffect(pixels);</pre><pre>// 將像素資訊設定回畫布<br>ctx.putImageData(pixels, 0 , 0);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*Fsnet5tUTN3RTf53zZkLAQ.png" /></figure><ul><li>利用 ctx.getImageData(0, 0, width, height) 取得像素資訊。</li><li>製作不同濾鏡效果，即是撰寫不同 function (如下一個步驟要寫的 redEffect、rgbSplit 和 greenScreen)來改變像素資訊數值。</li><li>ctx.putImageData 可將像素資訊設定回 canvas 畫布中。</li></ul><p><strong>1. 紅色特效 : redEffect</strong></p><p>剛剛利用 ctx.getImageData(0, 0, width, height) 所取得的像素資訊，會是一個非常大的陣列 — Uint8ClampedArray（8位無符號整型固定數組）。陣列裡面的數值會以 4 個為一組，分別代表 rgba</p><ul><li>紅（Red）</li><li>綠（Green）</li><li>藍（Blue）</li><li>Alpha通道（Alpha）</li></ul><p>透過改變這些數值，即可做出不同濾鏡效果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/516/1*PEOlI6SezIEUIAVBmI-Ccw.png" /></figure><p>紅色特效 redEffect 的製作方法，即是調整 rgb 數值，讓畫面轉紅</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/627/1*z0ArLjGj3i9788HTKaxaUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*QLJJmWVq_MM2rkuMZxzSKQ.png" /><figcaption>課程影片截圖 - 套用 redEffect 效果</figcaption></figure><p><strong>2. rgb 分散特效 : rgbSplit</strong></p><p><strong>rgbSplit</strong> 則是將不同像素的數值向前或向後移動，來達到畫面中紅、藍、綠位置分散的效果。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*jckJCp3Y2UElKsUU4O2rYw.png" /></figure><p>還可以在套用 rgbSplit 效果後，設定 ctx.globalAlpha = 0.1; 來疊加透明度，製作出霧霧的、👻影幢幢的效果</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/610/1*SSHrkOQ1DGi5gqvMOtGOXw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/765/1*2_UUmkTccmwXsbfaI5FYDw.png" /><figcaption>課程影片截圖 - <strong>rgbSplit </strong>加上 ctx.globalAlpha = 0.1; 之前</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/838/1*xTmzxVnN0gzg5YhFz19eeg.png" /><figcaption>課程影片截圖 - <strong>rgbSplit </strong>加上 ctx.globalAlpha = 0.1; 之後</figcaption></figure><p><strong>3. 綠幕效果 : greenScreen</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/505/1*j00YRV0MXrFafabJONPxww.png" /><figcaption>頁面左上方的 range input</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*G0C8uR_dbS_umzyf2wiMlg.png" /></figure><ul><li>首先，取得當前頁面左上方 input 所調整的數值，存取於 levels 物件中。</li><li>接著跑迴圈去取得影像像素資訊 (pixels) 內的 rgba 數值</li><li>一一判斷，比對是否落在我們用 range input 所設定的最大、最小 rgba 數值 (剛剛已儲存在 levels 物件內) 區間，如果落在區間，就將該四個一組的最後數值(Alpha)設為 0。</li></ul><p>就可以製做出綠幕效果 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/1*HD07rqnKlH8MexIyD8X-rw.png" /><figcaption>課程影片截圖 — 套用 <strong>greenScreen</strong> 效果</figcaption></figure><p>本次練習就到這邊結束囉~</p><p>由於使用到一些平常較少用到的影像、圖像、CANVAS 相關的用法，感覺十分陌生，所以相較於其他練習，也花了較多的時間去熟悉、進入狀況。</p><p>但很開心又完成了一個有趣的 JS 小練習^^</p><h4>完整 JS 程式碼</h4><pre>const video = document.querySelector(&#39;.player&#39;);<br>const canvas = document.querySelector(&#39;.photo&#39;);<br>const ctx = canvas.getContext(&#39;2d&#39;);<br>const strip = document.querySelector(&#39;.strip&#39;);<br>const snap = document.querySelector(&#39;.snap&#39;);</pre><pre>function getVideo() {<br>  navigator.mediaDevices.getUserMedia({ video: true, audio: false })<br>  .then(localMediaStream =&gt; {<br>    console.log(localMediaStream);<br>    video.srcObject = localMediaStream;<br>    video.play();<br>  })<br>  .catch(err =&gt; {<br>    console.error(`OH NO!!!`, err);<br>  });<br>}</pre><pre>function paintToCanvas() {<br>  const width = video.videoWidth;<br>  const height = video.videoHeight;<br>  canvas.width = width;<br>  canvas.height = height;<br>  return setInterval(() =&gt; {<br>    ctx.drawImage(video, 0, 0, width, height);<br>    // take the pixels out<br>    let pixels = ctx.getImageData(0, 0, width, height);<br>    // mess with them<br>    // pixels = redEffect(pixels);<br>    <br>    pixels = rgbSplit(pixels);<br>    // ctx.globalAlpha = 0.8;<br>    <br>    // pixels = greenScreen(pixels);<br>    // put them back<br>    ctx.putImageData(pixels, 0, 0);<br>  }, 16);<br>}</pre><pre>function takePhoto() {<br>  // played the sound<br>  snap.currentTime = 0;<br>  snap.play();<br>  <br>  // take the data out of the canvas<br>  const data = canvas.toDataURL(&#39;image/jpeg&#39;);<br>  const link = document.createElement(&#39;a&#39;);<br>  link.href = data;<br>  link.setAttribute(&#39;download&#39;, &#39;handsome&#39;);<br>  link.innerHTML = `&lt;img src=&quot;${data}&quot; alt=&quot;Handsome Man&quot; /&gt;`;<br>  strip.insertBefore(link, strip.firstChild);<br>}</pre><pre>function redEffect(pixels) {<br>  for (let i = 0; i &lt; pixels.data.length; i+=4) {<br>    pixels.data[i + 0] = pixels.data[i + 0] + 200; // RED<br>    pixels.data[i + 1] = pixels.data[i + 1] - 50; // GREEN<br>    pixels.data[i + 2] = pixels.data[i + 2] * 0.5; // Blue<br>  }<br>  return pixels;<br>}</pre><pre>function rgbSplit(pixels) {<br>  for (let i = 0; i &lt; pixels.data.length; i+=4) {<br>    pixels.data[i - 150] = pixels.data[i + 0]; // RED<br>    pixels.data[i + 500] = pixels.data[i + 1]; // GREEN<br>    pixels.data[i - 550] = pixels.data[i + 2]; // Blue<br>  }<br>  return pixels;<br>}</pre><pre>function greenScreen(pixels) {<br>  const levels = {};<br>  document.querySelectorAll(&#39;.rgb input&#39;).forEach((input) =&gt; {<br>    levels[input.name] = input.value;<br>  });<br>  for (i = 0; i &lt; pixels.data.length; i = i + 4) {<br>    red = pixels.data[i + 0];<br>    green = pixels.data[i + 1];<br>    blue = pixels.data[i + 2];<br>    alpha = pixels.data[i + 3];<br>    if (red &gt;= levels.rmin<br>      &amp;&amp; green &gt;= levels.gmin<br>      &amp;&amp; blue &gt;= levels.bmin<br>      &amp;&amp; red &lt;= levels.rmax<br>      &amp;&amp; green &lt;= levels.gmax<br>      &amp;&amp; blue &lt;= levels.bmax) {<br>      // take it out!<br>      pixels.data[i + 3] = 0;<br>    }<br>  }<br>  return pixels;<br>}</pre><pre>getVideo();</pre><pre>video.addEventListener(&#39;canplay&#39;, paintToCanvas);</pre><h4>參考資料</h4><p><strong>範例檔案下載 :</strong></p><p><a href="https://github.com/wesbos/JavaScript30">GitHub - wesbos/JavaScript30: 30 Day Vanilla JS Challenge</a></p><p><strong>JavaScript 30 課程註冊連結(輸入 email 免費註冊) :</strong></p><p><a href="https://javascript30.com/">JavaScript 30</a></p><p><strong>筆記參考 :</strong></p><ul><li><a href="https://ithelp.ithome.com.tw/articles/10248451?sc=iThomeR">Day20 -- WebCam - iT 邦幫忙::一起幫忙解決難題，拯救 IT 人的一天</a></li><li><a href="https://github.com/dustinhsiao21/Javascript30-dustin/tree/master/19%20-%20Webcam%20Fun">Javascript30-dustin/19 - Webcam Fun at master · dustinhsiao21/Javascript30-dustin</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fab2f2d7517a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ivycodefive/javascript-30-day19-unreal-webcam-fun-fab2f2d7517a">[JavaScript 30]Day19-Unreal Webcam Fun</a> was originally published in <a href="https://medium.com/ivycodefive">IvyCodeFive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JavaScript 30]Day18-Tally String Times with Reduce]]></title>
            <link>https://medium.com/ivycodefive/javascript-30-day18-tally-string-times-with-reduce-79db01eb4cf7?source=rss-3691ce586f53------2</link>
            <guid isPermaLink="false">https://medium.com/p/79db01eb4cf7</guid>
            <category><![CDATA[前端筆記]]></category>
            <category><![CDATA[js30]]></category>
            <category><![CDATA[學習筆記]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ivy Ho]]></dc:creator>
            <pubDate>Sat, 20 Aug 2022 08:49:17 GMT</pubDate>
            <atom:updated>2022-08-20T08:49:17.883Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPkSYwkdClnZLStSHWTxBQ.png" /></figure><p>今天要練習的是，如何將 Playlists 內所有格式為「00:00」的影片時間加總，計算出總共的時間為幾時幾分幾秒。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*9zW_Kt3PWEQT-737YV0EFA.png" /><figcaption>課程中的示意圖，非練習範例畫面</figcaption></figure><h4>學習重點</h4><ul><li>NodeList 轉 Array : [… ]、Array.from()</li><li>資料處理，組成新陣列 : .map()</li><li>分割字串 : .split()</li><li>加總 : .reduce()</li><li>無條件捨去小數，取整數 : Math.floor()</li><li><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Operators/Remainder">餘數運算子: &quot;%&quot;</a></li></ul><h4>觀察範例檔案初始狀態</h4><p><strong>HTML</strong></p><p>範例中預設有一個 videos 列表，裡面的&lt;li&gt;項目都有 data-time 屬性，值為每段影片的時間。</p><pre>&lt;ul class=&quot;videos&quot;&gt;<br>  &lt;li data-time=&quot;5:43&quot;&gt;<br>    Video 1<br>  &lt;/li&gt;<br>  &lt;li data-time=&quot;2:33&quot;&gt;<br>    Video 2<br>  &lt;/li&gt;<br>  &lt;li data-time=&quot;3:45&quot;&gt;<br>    Video 3<br>  &lt;/li&gt;<br>  &lt;li data-time=&quot;0:47&quot;&gt;<br>    Video 4<br>  &lt;/li&gt;<br>  &lt;li data-time=&quot;5:21&quot;&gt;<br>    Video 5<br>  &lt;/li&gt;<br>.<br>.<br>.</pre><pre>&lt;/ul&gt;</pre><p><strong>(最後完成的完整 JS 程式碼，以及檔案下載、課程連結，將放在最下方)</strong></p><h4>步驟拆解</h4><ol><li>取得 NodeList，並轉成 Array</li><li>取得每個節點內的 data-time 屬性值</li><li>取得分、秒，轉成數字，並計算成總秒數</li><li>將所有影片的秒數加總</li><li>將總秒數換算成 「時:分:秒」 格式</li></ol><h4>1. 取得 NodeList，並轉成 Array</h4><ul><li>抓取含有 data-time 屬性的所有節點，querySelectorAll 所取得的會是一個 NodeList。</li><li>利用 Array.from() 或 [… ] 方法將 NodeList 轉為陣列。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OV3UDO_yoA5eOe-vRAQaNw.png" /></figure><h4>2. 取得每個節點內的 data-time 屬性值</h4><ul><li>利用 .dataset.time 取得屬性值。</li><li>利用 .map() 方法將所有 data-time 屬性值組成一個新的陣列。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*183jPPoIMAztCNlqBVYW2g.png" /></figure><p>利用 console.log 查看目前取得的資料狀態 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/467/1*nnGx1uWZdq2Vngckt1qWhA.png" /></figure><h4>3. 取得分、秒，轉成數字，並計算成總秒數</h4><ul><li>一樣使用 .map() 方法。</li><li>利用 .split(&#39;:&#39;) 來分割冒號兩邊的數字(字串)。</li><li>.map() 內可以直接呼叫 parseFloat 方法，便可將字串轉為數字。</li><li>利用 ES6 解構附值寫法分別取得 分(mins), 秒(secs)。</li><li>在下方進行運算，將分鐘換算成秒數後加總，並作為返回值。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tImgY9e_BeNMo0-fw_mPOQ.png" /></figure><p>利用 console.log 查看目前取得的資料狀態 :</p><p>會得到每一個影片的總秒數，所組成的陣列</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/374/1*w8iltpLTYU62zYu-yDA7NA.png" /></figure><h4>4. 將所有影片的秒數加總</h4><ul><li>利用 .reduce 方法將所有陣列內的秒數加總</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JV799EFUYWRLCSFtHQuOfQ.png" /></figure><p>利用 console.log 查看是否得到總秒數 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/211/1*9zv-fSivrl3fRUNkSydz4w.png" /></figure><h4>5. 將總秒數換算成 「時:分:秒」 格式</h4><ul><li>將秒數除以 3600，換算成小時。利用 Math.floor() 取整數。</li><li>餘數運算子% 可取得剩餘秒數。</li><li>分鐘數的算法與上述相似。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I6sAajTGBcpORnRHb1wfaw.png" /></figure><p>最後就能得到所有影片的總時間，為幾時幾分幾秒。</p><p>console.log 查看剛剛計算出來的 hours, mins, secondsLeft :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/202/1*RUHwEPxMAVfdDHdpyJ2g4w.png" /></figure><p>今天的練習就到這邊結束囉~</p><h4>完整 JS 程式碼</h4><pre>const timeNodes = Array.from(document.querySelectorAll(&#39;[data-time]&#39;));</pre><pre>const seconds = timeNodes<br>  .map(node =&gt; node.dataset.time)<br>  .map(timeCode =&gt; {<br>    const [mins, secs] = timeCode.split(&#39;:&#39;).map(parseFloat);<br>    return (mins * 60) + secs;<br>  })<br>  .reduce((total, vidSeconds) =&gt; total + vidSeconds);</pre><pre>let secondsLeft = seconds;<br>const hours = Math.floor(secondsLeft / 3600);<br>secondsLeft = secondsLeft % 3600;<br>const mins = Math.floor(secondsLeft / 60);<br>secondsLeft = secondsLeft % 60;<br>console.log(hours, mins, secondsLeft);</pre><h4>參考資料</h4><p>範例檔案下載 :</p><p><a href="https://github.com/wesbos/JavaScript30">GitHub - wesbos/JavaScript30: 30 Day Vanilla JS Challenge</a></p><p>JavaScript 30 課程註冊連結(輸入 email 免費註冊) :</p><p><a href="https://javascript30.com/">JavaScript 30</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=79db01eb4cf7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ivycodefive/javascript-30-day18-tally-string-times-with-reduce-79db01eb4cf7">[JavaScript 30]Day18-Tally String Times with Reduce</a> was originally published in <a href="https://medium.com/ivycodefive">IvyCodeFive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JavaScript 30]Day17-Sorting Band Names without articles]]></title>
            <link>https://medium.com/ivycodefive/javascript-30-day17-sorting-band-names-without-articles-19d4ec3ceb3d?source=rss-3691ce586f53------2</link>
            <guid isPermaLink="false">https://medium.com/p/19d4ec3ceb3d</guid>
            <category><![CDATA[前端筆記]]></category>
            <category><![CDATA[學習筆記]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[js30]]></category>
            <dc:creator><![CDATA[Ivy Ho]]></dc:creator>
            <pubDate>Sat, 23 Jul 2022 15:18:58 GMT</pubDate>
            <atom:updated>2022-07-23T15:18:58.125Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPkSYwkdClnZLStSHWTxBQ.png" /></figure><p>今天要練習依照字母開頭，排序一組陣列內的樂團名稱，且須過濾掉不必要的 &quot;The, A, AN&quot; 開頭，再進行排序，最後將陣列轉成 html 字串，顯示於頁面上。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rF52Uv1b9MDwi_Pb1RvpEg.png" /></figure><h4>學習重點</h4><ul><li>排序 : <a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">.sort()</a></li><li>過濾、篩選 : <a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/String/replace">.replace()</a> + <a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Guide/Regular_Expressions">正規表達式</a></li><li>組成 html 字串 : <a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/map">.map()</a>、<a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/join">.join(&#39;&#39;)</a></li></ul><h4>觀察範例檔案初始狀態</h4><p><strong>HTML</strong></p><pre>&lt;ul id=&quot;bands&quot;&gt;&lt;/ul&gt;</pre><p><strong>CSS</strong></p><p>已有預先寫好的樣式，但今天練習只著重在 JS 資料處理，需要樣式的話，可至最底下連結下載。</p><p><strong>JS</strong></p><p>已有一個包含所有樂團名稱的 bands 陣列 :</p><pre>const bands = [&#39;The Plot in You&#39;, &#39;The Devil Wears Prada&#39;, &#39;Pierce the Veil&#39;, &#39;Norma Jean&#39;, &#39;The Bled&#39;, &#39;Say Anything&#39;, &#39;The Midway State&#39;, &#39;We Came as Romans&#39;, &#39;Counterparts&#39;, &#39;Oh, Sleeper&#39;, &#39;A Skylit Drive&#39;, &#39;Anywhere But Here&#39;, &#39;An Old Dog&#39;];</pre><p><strong>(最後完成的完整 JS 程式碼，以及檔案下載、課程連結，將放在最下方)</strong></p><h4>解決思路</h4><p>一、排序</p><p>二、製作一個過濾器，過濾掉不需要的 &quot;The, A, AN&quot;</p><p>三、顯示於頁面上</p><h4>一、排序</h4><p>直接使用 .sort() 對 bands 陣列做排序</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GJwhaj6FI_u2gEIQNt2IiA.png" /></figure><p>會得到以下結果 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/293/1*W22Skk02KZWL5SBNa0w6sg.png" /></figure><p>但我們希望能過濾掉 &quot;The, A, AN&quot; 這些開頭，再做排序。</p><h4>二、製作一個過濾器，過濾掉不需要的 “The, A, AN”</h4><p>我們可以透過使用 .replace() + 正規表達式，製作一個 strip 方法作為過濾器，並且只套用在比對時的 a、b 上，而不是去改變一整個原本的陣列。</p><p>利用 .replace() + 正規表達式，將 &quot;The, A, AN&quot; 用空字串取代，再利用 .trim() 去除空格。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d1gjGFXR-zEPQjOJWlEbIA.png" /></figure><p>這時候的資料就能變成我們希望呈現的順序 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/294/1*BePTj7UzIDALY0tmUL3_hg.png" /></figure><p>而上面這段 sortedBands 程式碼，也可以利用三元運算子及 ES6 箭頭函式寫法，簡寫為一行 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oKBgmQo6PBj-6SlD3UPDcw.png" /></figure><h4>三、顯示於頁面上</h4><p>最後我們要將剛剛排序好的陣列資料顯示於頁面。</p><ol><li>將剛剛排序完成的 sortedBands 陣列利用 .map() 重新組成帶有一項一項 html 字串的新陣列。</li><li>利用 .join(&#39;&#39;) 將陣列內一項一項的字串，連接、合併成一個大字串。</li><li>抓取 html 的 &lt;ul id=&quot;bands&quot;&gt;&lt;/ul&gt; 元素 DOM。</li><li>利用 innerHTML 的方法，顯示於頁面上。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FRKW1sGXFdfSeDSmwufCVw.png" /></figure><p>到這邊就完成今天的小練習囉~</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rF52Uv1b9MDwi_Pb1RvpEg.png" /></figure><h4>完整 JS 程式碼</h4><pre>const bands = [&#39;The Plot in You&#39;, &#39;The Devil Wears Prada&#39;, &#39;Pierce the Veil&#39;, &#39;Norma Jean&#39;, &#39;The Bled&#39;, &#39;Say Anything&#39;, &#39;The Midway State&#39;, &#39;We Came as Romans&#39;, &#39;Counterparts&#39;, &#39;Oh, Sleeper&#39;, &#39;A Skylit Drive&#39;, &#39;Anywhere But Here&#39;, &#39;An Old Dog&#39;];</pre><pre>function strip(bandName) {<br>  return bandName.replace(/^(a |the |an )/i, &#39;&#39;).trim();<br>}</pre><pre>const sortedBands = bands.sort((a, b) =&gt; strip(a) &gt; strip(b) ? 1 : -1);</pre><pre>document.querySelector(&#39;#bands&#39;).innerHTML =</pre><pre>  sortedBands</pre><pre>    .map(band =&gt; `&lt;li&gt;${band}&lt;/li&gt;`)</pre><pre>    .join(&#39;&#39;);</pre><pre>console.log(sortedBands);</pre><h4>參考資料</h4><p>範例檔案下載 :</p><p><a href="https://github.com/wesbos/JavaScript30">GitHub - wesbos/JavaScript30: 30 Day Vanilla JS Challenge</a></p><p>JavaScript 30 課程註冊連結(輸入 email 免費註冊) :</p><p><a href="https://javascript30.com/">JavaScript 30</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=19d4ec3ceb3d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ivycodefive/javascript-30-day17-sorting-band-names-without-articles-19d4ec3ceb3d">[JavaScript 30]Day17-Sorting Band Names without articles</a> was originally published in <a href="https://medium.com/ivycodefive">IvyCodeFive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JavaScript 30]Day16-CSS Text Shadow Mouse Move Effect]]></title>
            <link>https://medium.com/ivycodefive/javascript-30-day16-css-text-shadow-mouse-move-effect-2472f137439?source=rss-3691ce586f53------2</link>
            <guid isPermaLink="false">https://medium.com/p/2472f137439</guid>
            <category><![CDATA[js30]]></category>
            <category><![CDATA[學習筆記]]></category>
            <category><![CDATA[前端筆記]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ivy Ho]]></dc:creator>
            <pubDate>Thu, 07 Jul 2022 15:04:50 GMT</pubDate>
            <atom:updated>2022-07-07T15:41:46.250Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPkSYwkdClnZLStSHWTxBQ.png" /></figure><p>今天要練習如何偵測到滑鼠移動位置，進而利用 JS 動態改變 CSS 樣式，製作出<strong>「隨著滑鼠移動，會變換位置的陰影效果」</strong>。</p><p>鼠標移動至 &lt;h1&gt; 字樣中心 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6O933nMEFY18l_Ud4GiNuQ.png" /></figure><p>鼠標在 &lt;h1&gt; 字樣周圍移動，不同顏色的陰影樣式，位置會跟著產生變化 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OEsLJYTzteVkagrOotLFsw.png" /></figure><h4>學習重點</h4><ul><li>監聽 mousemove 事件</li><li>ES6 解構賦值</li><li>offsetWidth 、offsetHeight : 元素寬、高</li><li>offsetLeft 、offsetTop : 元素左邊、上面與 offsetParent 的距離</li><li>e.offsetX、e.offsetY : 滑鼠距離元素左上角的 X、Y 軸距離</li><li>Math.round() : 回傳四捨五入後的近似值</li></ul><h4>觀察範例檔案初始狀態</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/763/1*rhXwP3cIAWKmhqaNeRyRqw.png" /></figure><h4><strong>HTML</strong></h4><p>html 有個簡單的結構 ，.hero 裡包著一個 &lt;h1&gt;</p><pre>&lt;div class=&quot;hero&quot;&gt;<br>   &lt;h1 contenteditable&gt;🔥WOAH!&lt;/h1&gt;<br>&lt;/div&gt;</pre><h4>CSS</h4><ul><li>根據 CSS 設定，.hero 是佔滿整個瀏覽器視窗範圍的狀態。</li><li>範例預先在 h1 加上了一個 <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow">text-shadow</a> 樣式，可能是方便讓我們了解設定方法。之後用 JS 加上其他陰影效果後，可以將原先在 CSS 內的這段 text-shadow 設定刪除。</li></ul><pre>.hero {</pre><pre>  min-height: 100vh;</pre><pre>  display: flex;</pre><pre>  justify-content: center;</pre><pre>  align-items: center;</pre><pre>  color: black;</pre><pre>}</pre><pre>h1 {</pre><pre>  text-shadow: 10px 10px 0 rgba(0,0,0,1);</pre><pre>  font-size: 100px;</pre><pre>}</pre><p><strong>(最後完成的完整 JS 程式碼，以及檔案下載、課程連結，將放在最下方)</strong></p><h4>步驟拆解</h4><p>一、對 .hero 監聽 mousemove 事件</p><p>二、取得 .hero 在視窗上的寬高範圍，以及動態滑鼠座標</p><p>三、整合鼠標進入&lt;h1&gt; 範圍內的座標</p><p>四、將滑鼠座標數值，轉換為想設定的樣式 px 範圍</p><p>五、調整陰影位置</p><p>六、加入多種顏色、不同位置的陰影樣式</p><h4>一、對 .hero 監聽 mousemove 事件</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*1QuL0ge_As8P_EsikGv4Sw.png" /></figure><h4>二、取得 .hero 在視窗上的寬高範圍，以及動態滑鼠座標</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/1*hN1gIL8Q3S2Ph3YQpVs_dQ.png" /></figure><p><strong>[小補充] ES6 解構賦值寫法 :</strong></p><pre>const width = hero.offsetWidth;<br>const height = hero.offsetHeight;<br>  <br>// 可簡寫成 <br>const { offsetWidth: width, offsetHeight: height} = hero;</pre><p>===</p><pre>let x = e.offsetX;<br>let y = e.offsetY;</pre><pre>// 可簡寫成<br>let { offestX: x, offsetY: y } = e;</pre><h4>三、整合鼠標進入 &lt;h1&gt; 範圍內的座標</h4><p>當我們用 console.log(x, y) 組成座標，觀察滑鼠座標的變化，會發現當鼠標移動進 &lt;h1&gt; 範圍內的左上角，座標又會從(0 , 0) 開始變化。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*9_WmXTTBNj7QntWYPY6DQg.png" /><figcaption>為了方便識別 h1 範圍，將 h1 的背景色暫時改為紅色</figcaption></figure><p><strong>問題 :</strong></p><p>雖然我們是對 .hero 監聽 mousemove 事件，但 .hero 裡面有包裹一個子層，也就 &lt;h1&gt;，當滑鼠移動到 &lt;h1&gt; 範圍內，<strong>e.target 將會改變為子層的 </strong><strong>&lt;h1&gt;</strong>，回傳的 e.offsetX、e.offsetY，也會變成在 &lt;h1&gt; 範圍內的座標。</p><p><strong>解決方法:</strong></p><p>為了防止鼠標進入 &lt;h1&gt; 範圍後，變成以&lt;h1&gt; 範圍為基準的相對座標，我們可以想辦法偵測<strong>當鼠標進入 </strong><strong>&lt;h1&gt; 範圍後，就將 </strong><strong>&lt;h1&gt; 距離視窗左邊的寬度，以及距離上方的高度，補進座標數值內。</strong>如此一來，我們抓到的座標就得以連貫。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/958/1*A3hVNtnS5O1TSuOnsNhAxg.png" /></figure><p><strong>如何判斷鼠標進入到 </strong><strong>&lt;h1&gt; 範圍內了?</strong></p><p>因為我們是對 .hero 監聽 mousemove 事件，所以 shadow() 函式內的 this 會指向 .hero 。</p><p>但 e.target 會隨著鼠標移動至 .hero 或 &lt;h1&gt; 的範圍，而有所改變。</p><p>所以我們可以用 if(this !== e.target) {} 來判斷，當 e.target 不等於 .hero，就表示此時鼠標已經移進 &lt;h1&gt; 的範圍內。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*Rqu9YIFXUI1fi51z9T5hxQ.png" /></figure><h4>四、將滑鼠座標數值，轉換為想設定的樣式 px 範圍</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*-wRZWXYrQvEM2M1Q9ef0GQ.png" /></figure><p><strong>1. 宣告 walk 變數，設定範圍</strong></p><p>我們希望陰影樣式的位置，變化範圍在 100 px 內</p><pre>const walk = 100;</pre><p><strong>2. 計算陰影位置座標數值</strong></p><ul><li>xWalk 計算原理 : <br>將 x / width ，可以得到「目前 x 座標數值」佔「 .hero 寬度範圍」的百分比，再將它乘上 walk，即可算出<strong>滑鼠移動到任意 x 座標時，陰影樣式會變化到距離原字樣多少 px 的位置</strong>。<br>再使用 Math.round() 取得四捨五入後的整數。</li><li>yWalk 計算原理與 xWalk 相似。</li></ul><pre>const xWalk = Math.round((x / width * walk));</pre><pre>const yWalk = Math.round((y / height * walk));</pre><p><strong>3. 為 </strong><strong>&lt;h1&gt; 加上 CSS 陰影樣式</strong></p><p>帶入剛剛計算的 xWalk、yWalk，作為陰影樣式的前兩個設定值。<br>隨著鼠標移動，xWalk、yWalk 數值也會變化，進而造成陰影位置變化，形成動態效果。</p><pre>text.style.textShadow = `${xWalk}px ${yWalk}px 0 red`;</pre><h4>五、調整陰影位置</h4><p><strong>問題 :</strong></p><p>此時的紅色陰影樣式，雖然會隨著鼠標變換位置，但效果並非我們所預期。</p><p>鼠標移至視窗右下角 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-lLDOP7zycTl0kpfU5x_-g.png" /></figure><p>鼠標移至視窗左上角 :</p><p>希望紅色陰影在黑字樣的左上方，但呈現的效果卻是與黑字重疊</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uwjA2E1DTCXTCvi6tHvvqg.png" /></figure><p>因為我們目前的設定，會讓陰影位置的數值變化如下 :</p><p>鼠標移至右下角 =&gt; 陰影 CSS : text-shadow: 100px 100px 0px red;</p><p>鼠標移至左上角 =&gt; 陰影 CSS : text-shadow: 0px 0px 0px red;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1R4sHKMvSuR_LSsxoTGfrg.png" /></figure><p>而我們想要的效果，應該要<strong>以 </strong><strong>&lt;h1&gt; 字樣中心為基準點</strong>，去做相對位置數值的變化</p><p>鼠標移至右下角 =&gt; 陰影 CSS : text-shadow: 50px 50px 0px red;</p><p>鼠標移至左上角 =&gt; 陰影 CSS : text-shadow: -50px -50px 0px red;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-DvcW2sCdbdvokFpbjClPA.png" /></figure><p><strong>解決方法 :</strong></p><p>在 xWalk、yWalk 的計算式，分別都再減去二分之一的 walk 值 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/883/1*SeEqO0MF4YpWGCX5exMiuA.png" /></figure><p>如此一來，陰影位置，就可以以 &lt;h1&gt; 字樣中心點去做變化。</p><p>鼠標移至視窗左上角，陰影位置能成功往左上方移動 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8rKA4CNGwnP8EjhGaKbFuA.png" /></figure><h4>六、加入多種顏色、不同位置的陰影樣式</h4><p>text-shadow 可設定多層的陰影，將每層陰影設定不同顏色，並在 x、y 軸數值上做一點小變化，讓不同顏色的陰影朝不同方向、位置做變化。</p><pre>text.style.textShadow = `</pre><pre>  ${xWalk}px ${yWalk}px 0 rgba(255,0,255,0.7),</pre><pre>  ${xWalk * -1}px ${yWalk}px 0 rgba(0,255,255,0.7),</pre><pre>  ${yWalk}px ${xWalk * -1}px 0 rgba(0,255,0,0.7),</pre><pre>  ${yWalk * -1}px ${xWalk}px 0 rgba(0,0,255,0.7)</pre><pre>`;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/884/1*hsTi9IlMMURBABDTqJ-DhA.png" /></figure><p>就能完成今天範例的效果 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*OEsLJYTzteVkagrOotLFsw.png" /></figure><p>也可以玩玩不同陰影樣式，例如讓它呈現霓虹燈光暈的效果，並隨著鼠標往不同方向移動 :</p><pre>text.style.textShadow = `</pre><pre>  ${xWalk}px ${yWalk}px 5px white,</pre><pre>  ${xWalk}px ${yWalk}px 10px white,</pre><pre>  ${xWalk}px ${yWalk}px 15px white,</pre><pre>  ${xWalk}px ${yWalk}px 40px #ff6723,</pre><pre>  ${xWalk}px ${yWalk}px 70px #ff6723</pre><pre>`;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*PcKWHRhovsyH9MxeaU2x-g.png" /></figure><p>今天的練習就到這邊結束囉~</p><h4>完整 JS 程式碼</h4><pre>const hero = document.querySelector(&#39;.hero&#39;);<br>const text = hero.querySelector(&#39;h1&#39;);<br>const walk = 500; // 500px</pre><pre>function shadow(e) {<br>  const { offsetWidth: width, offsetHeight: height } = hero;<br>  let { offsetX: x, offsetY: y } = e;<br>  if (this !== e.target) {<br>    x = x + e.target.offsetLeft;<br>    y = y + e.target.offsetTop;<br>  }<br>  const xWalk = Math.round((x / width * walk) - (walk / 2));<br>  const yWalk = Math.round((y / height * walk) - (walk / 2));<br>  text.style.textShadow = `<br>    ${xWalk}px ${yWalk}px 0 rgba(255,0,255,0.7),<br>    ${xWalk * -1}px ${yWalk}px 0 rgba(0,255,255,0.7),<br>    ${yWalk}px ${xWalk * -1}px 0 rgba(0,255,0,0.7),<br>    ${yWalk * -1}px ${xWalk}px 0 rgba(0,0,255,0.7)<br>  `;<br>}<br>hero.addEventListener(&#39;mousemove&#39;, shadow);</pre><h3>參考資料</h3><p>範例檔案下載 :</p><p><a href="https://github.com/wesbos/JavaScript30">GitHub - wesbos/JavaScript30: 30 Day Vanilla JS Challenge</a></p><p>JavaScript 30 課程註冊連結(輸入 email 免費註冊) :</p><p><a href="https://javascript30.com/">JavaScript 30</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2472f137439" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ivycodefive/javascript-30-day16-css-text-shadow-mouse-move-effect-2472f137439">[JavaScript 30]Day16-CSS Text Shadow Mouse Move Effect</a> was originally published in <a href="https://medium.com/ivycodefive">IvyCodeFive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JavaScript 30]Day15-LocalStorage and Event Delegation]]></title>
            <link>https://medium.com/ivycodefive/javascript-30-day15-localstorage-and-event-delegation-122047726fc6?source=rss-3691ce586f53------2</link>
            <guid isPermaLink="false">https://medium.com/p/122047726fc6</guid>
            <category><![CDATA[js30]]></category>
            <category><![CDATA[學習筆記]]></category>
            <category><![CDATA[前端筆記]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ivy Ho]]></dc:creator>
            <pubDate>Sun, 19 Jun 2022 08:48:21 GMT</pubDate>
            <atom:updated>2022-06-19T08:54:25.419Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPkSYwkdClnZLStSHWTxBQ.png" /></figure><p>今天要練習製作一個可新增、勾選的 to-do list，並將新增的項目以及勾選狀態存入 localStorage 內。練習中也能了解到 Event Delegation (事件指派)的觀念。</p><h4>功能需求</h4><ol><li>可新增、勾選項目</li><li>重整後項目仍然存在</li><li>記錄勾選狀態</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dial57KhOiwWO4Qf-vkT6Q.png" /></figure><h4>學習重點</h4><ul><li>監聽 submit 事件</li><li><strong>localStorage</strong></li></ul><p>1. 存入 : localStorage.setItem()</p><p>2. 取出: localStorage.getItem()</p><p>3. JSON 轉字串 : JSON.stringify()</p><p>4. JSON 轉回原資料型態 : JSON.parse()</p><ul><li>Event Delegation</li><li>.map()</li><li>.join(&#39;&#39;)</li><li>data-set</li><li>.matches(&#39;&#39;)</li></ul><h4>觀察範例檔案初始狀態</h4><p><strong>HTML</strong></p><ul><li>等等將會對 .plates 以及 .add-items 進行操作</li><li>.plates 內已有一個示意的 &lt;li&gt; 項目</li></ul><pre>&lt;div class=&quot;wrapper&quot;&gt;</pre><pre>  &lt;h2&gt;LOCAL TAPAS&lt;/h2&gt;</pre><pre>  &lt;p&gt;&lt;/p&gt;</pre><pre>  &lt;ul class=&quot;plates&quot;&gt;</pre><pre>    &lt;li&gt;Loading Tapas...&lt;/li&gt;</pre><pre>  &lt;/ul&gt;</pre><pre>  &lt;form class=&quot;add-items&quot;&gt;</pre><pre>    &lt;input type=&quot;text&quot; name=&quot;item&quot; placeholder=&quot;Item Name&quot; required&gt;</pre><pre>    &lt;input type=&quot;submit&quot; value=&quot;+ Add Item&quot;&gt;</pre><pre>  &lt;/form&gt;</pre><pre>&lt;/div&gt;</pre><p><strong>CSS</strong></p><p>已有一些基本的樣式設定，以及以下的 checkbox 圖形切換設定 :</p><pre>.plates input + label:before {</pre><pre>  content: &quot;⬜️&quot;;</pre><pre>  margin-right: 10px;</pre><pre>}</pre><pre>.plates input:checked + label:before {</pre><pre>  content: &quot;🌮&quot;;</pre><pre>}</pre><p><strong>JS</strong></p><ul><li>預先抓好了 .add-items 和 .plates 的 DOM</li><li>愈先定義資料 items 為一空陣列</li></ul><pre>const addItems = document.querySelector(&#39;.add-items&#39;);</pre><pre>const itemsList = document.querySelector(&#39;.plates&#39;);</pre><pre>const items = [];</pre><p><strong>(最後完成的完整 JS 程式碼，以及檔案下載、課程連結，將放在最下方)</strong></p><h4>解決思路</h4><p>一、取得 input 輸入的值，並將資料新增至一個陣列內</p><p>二、將新增的項目顯示於畫面上</p><p>三、將資料存入 localStorage 中，並在刷新頁面、新增項目後，從中取出</p><p>四、儲存 checkbox 的勾選狀態</p><h4>一、取得 input 輸入的值，並將資料新增至一個陣列內</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*zfBUVcqDSs2Z0-BgUdFppw.png" /></figure><ul><li>對 addItems 表單監聽 submit 事件，觸發 addItem。</li><li>取得 input 內輸入的內容。</li><li>組成 item 物件，加上 done 狀態布林值 。(用來切換勾選狀態)</li><li>將新增的物件 push 進 items 陣列中。</li><li>目前 addItem 事件內的 this 指向 addItems 這個&lt;form&gt;，而 &lt;form&gt;有 reset() 方法，所以我們可以透過 this.reset(); 來做到表單 submit 之後清空 input 內容。</li></ul><p><strong>小補充</strong></p><p>當物件的key 和 value 的變數名稱相同時，可以使用 ES6 的寫法，只寫變數名稱即可。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uIAlqx5f0lspiIGpIieidQ.png" /></figure><h4>二、將新增的項目顯示於畫面上</h4><p><strong>1. 新增一個 populateList function</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*IbWNK8nUKvOmeWOavJl4kw.png" /></figure><ul><li>在要傳入的參數位置，可以預設 plates = []以避免忘記傳入參數導致程式碼出錯。</li><li>利用 .map() 可以將 plates 陣列資料處理過後，回傳出一個新的陣列</li><li>經 .map() 處理過後的新陣列裡，一個項目是一段 html 字串，我們可以透過 .join(&#39;&#39;) 將他們全部合併成一個大字串。</li><li>再透過 .innerHTML 將剛剛組好的 html 字串放進 .plateList 裡，顯示於畫面上。</li></ul><p><strong>小補充</strong></p><ul><li>HTML 中只要有 checked 屬性，就會是 checked 的狀態，即便給它一個值 checked=&quot;false&quot;，也會顯示為已勾選。</li><li>所以可以透過 plate.done 狀態，來判斷是否加上 checked : ${plate.done ? &#39;checked&#39; : &#39;&#39;}</li><li>null 在 html 上會顯示出來，所以使用空字串 &#39;&#39; 來切換沒有 checked 的狀態</li><li>目前的作法是，新增一個項目就更新一整個列表至畫面上，如果資料更新並不頻繁，效能不會有太大問題。<br>但如果資料量龐大且更新頻繁，則可能需要考慮借助於 JS 框架的優點(虛擬 DOM + Diff 算法，盡量複用 DOM 節點)，讓列表在新增時，先與原本資料做比對，再單獨更新新增的項目。</li></ul><p><strong>2. 在上一個步驟新增的 addItems function 內，呼叫 populateList function</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*JaBCVEILhjswmOKL429-uw.png" /></figure><ul><li>傳入 items 和 itemsList 作為參數</li><li>將 populateList function 設計為需傳入第二個參數，而不是在 function 內直接使用全域變數中的 itemsList， 是為了讓這個 function 複用性更高，如果日後有兩份菜單列表，也可以用同一個 function 做處理。</li></ul><h4>三、將資料存入 localStorage 中，並在刷新頁面、新增項目後，從中取出</h4><ol><li><strong>資料存入 localStorage</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*DUa1kNSNXESICRQdQ7cfNA.png" /></figure><ul><li>在每一次新增時，我們可以使用 localStorage.setItem() 將資料存入 localStorage 裡面</li><li>而在 localStorage 中，資料型態雖然看起來也是由 key 和 value 組成，但只能使用 <strong>&quot;字串&quot;</strong> 的形式存入。<br>所以在存入之前，需使用 JSON.stryigify() 將資料型態轉為 JSON 字串 :</li></ul><pre>localStorage.setItem(&#39;items&#39;, JSON.stringify(items));</pre><ul><li>在 input 內輸入菜單項目後，我們可以打開 F12 &gt;Application &gt;Local Storage ，看到資料已存入 localStorage 內</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzWW5iW3lBp4eBk0sbXnYA.png" /></figure><p><strong>2. 資料從 localStorage 中取出</strong></p><ul><li>剛剛提到，在存入資料時，我們會先將資料用 JSON.stryigify() 轉為 JSON 字串再存入。取出時，則可以使用 JSON.parse() ，將資料轉回原來的資料型態。</li><li>在最一開始，我們有預設 items 為一個空陣列，現在可以改為，先從 localStorage 中嘗試取得，如果沒有資料，再預設為空陣列:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*TMh0vuW5DkyBg6V9q_z7zQ.png" /></figure><ul><li>此時當我們重整頁面，會看到畫面上，並沒有顯示我們已存入 localStorage 內的項目，需要再新增一個項目，才會顯示。</li><li>因此，我們可以在程式碼最底下 (外部全域環境) 再呼叫一次 populateList()，就能讓頁面重整後的一開始，就將 localStorage 內的資料顯示於畫面上。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/879/1*oVUdNtFh5pYN43u3OKSzXA.png" /></figure><h4>四、儲存 checkbox 的勾選狀態</h4><p>此時新增的項目雖然可勾選，但勾選狀態並沒有與我們的資料連動，需再新增以下這個 toggleDone function ，來同步存入、更新畫面 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*MUoFjTNwEZW5fK-Bj2CowA.png" /></figure><p><strong>小補充 : Event Delegation（事件指派）</strong></p><p>如果是跑迴圈對所有子層 &lt;li&gt; 元素監聽 click 事件，當我們再用 JS 新增新的 &lt;li&gt;項目，會發現<strong>新增的節點並不會有 click 事件的註冊</strong>。<br>更好的作法是，<strong>只監聽父層 </strong><strong>&lt;ul&gt; 一個元素</strong>，也就是 itemsList，再藉由 Event Bubbling 傳遞給子層，即為 <strong>Event Delegation（事件指派）</strong>的做法。</p><p>但當我們用事件指派的做法，通常需再判斷 e.target 是我們要的目標節點，再安排接續後續的事件內容。</p><p>如範例中，監聽了一整個 &lt;ul&gt;，再點擊 &lt;ul&gt; 範圍內的任意一處，會發現 e.target 所偵測點擊到的是 &lt;label&gt;、&lt;input&gt;、&lt;li&gt;等不同元素 :</p><pre>function toggleDone(e) {     <br>  console.log(e.target);<br>}</pre><pre>temsList.addEventListener(&#39;click&#39;, toggleDone);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*4xFXZI9LT2JkPz9aGaxSqA.png" /></figure><ul><li>我們更希望的是，當使用者點擊到的是 &lt;input&gt; 的位置，再觸發後續事件，也希望能獲取 input 上的 data-index 值，所以在前面會再加上一段判斷式 :</li></ul><pre>if(!e.target.matches(&#39;input&#39;)) return;</pre><p>到這邊就完成了今天的練習，頁面重整後，項目和勾選狀態，都會保存在 localStorage ，並顯示於畫面上。</p><h4>完整 JS 程式碼</h4><pre>const addItems = document.querySelector(&#39;.add-items&#39;);</pre><pre>const itemsList = document.querySelector(&#39;.plates&#39;);</pre><pre>const items = JSON.parse(localStorage.getItem(&#39;items&#39;)) || [];</pre><pre>function addItem(e) {</pre><pre>  e.preventDefault();</pre><pre>  const text = (this.querySelector(&#39;[name=item]&#39;)).value;</pre><pre>  const item = {</pre><pre>    text,</pre><pre>    done: false</pre><pre>  };</pre><pre>  items.push(item);</pre><pre>  populateList(items, itemsList);</pre><pre>  localStorage.setItem(&#39;items&#39;, JSON.stringify(items));</pre><pre>  this.reset();</pre><pre>}</pre><pre>function populateList(plates = [], platesList) {</pre><pre>  platesList.innerHTML = plates.map((plate, i) =&gt; {</pre><pre>    return `</pre><pre>      &lt;li&gt;</pre><pre>      &lt;input type=&quot;checkbox&quot; data-index=${i} id=&quot;item${i}&quot; ${plate.done ? &#39;checked&#39; : &#39;&#39;} /&gt;</pre><pre>      &lt;label for=&quot;item${i}&quot;&gt;${plate.text}&lt;/label&gt;</pre><pre>      &lt;/li&gt;</pre><pre>    `;</pre><pre>  }).join(&#39;&#39;);</pre><pre>}</pre><pre>function toggleDone(e) {</pre><pre>  if (!e.target.matches(&#39;input&#39;)) return;</pre><pre>  const el = e.target;</pre><pre>  const index = el.dataset.index;</pre><pre>  items[index].done = !items[index].done;</pre><pre>  localStorage.setItem(&#39;items&#39;, JSON.stringify(items));</pre><pre>  populateList(items, itemsList);</pre><pre>}</pre><pre>addItems.addEventListener(&#39;submit&#39;, addItem);</pre><pre>itemsList.addEventListener(&#39;click&#39;, toggleDone);</pre><pre>populateList(items, itemsList);</pre><h4>參考資料</h4><p><a href="https://ithelp.ithome.com.tw/articles/10192015">https://ithelp.ithome.com.tw/articles/10192015</a></p><ul><li><a href="https://cythilya.github.io/2015/07/08/javascript-event-delegation/">Event Delegation 事件委派 | Summer。桑莫。夏天</a></li><li><a href="https://github.com/wesbos/JavaScript30">GitHub - wesbos/JavaScript30: 30 Day Vanilla JS Challenge</a></li><li><a href="https://javascript30.com/">JavaScript 30</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=122047726fc6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ivycodefive/javascript-30-day15-localstorage-and-event-delegation-122047726fc6">[JavaScript 30]Day15-LocalStorage and Event Delegation</a> was originally published in <a href="https://medium.com/ivycodefive">IvyCodeFive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JS30筆記]-Day14 Object and Arrays — Reference VS Copy]]></title>
            <link>https://medium.com/ivycodefive/js30%E7%AD%86%E8%A8%98-day14-object-and-arrays-reference-vs-copy-97dd44ef6354?source=rss-3691ce586f53------2</link>
            <guid isPermaLink="false">https://medium.com/p/97dd44ef6354</guid>
            <category><![CDATA[學習筆記]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[前端筆記]]></category>
            <category><![CDATA[js30]]></category>
            <dc:creator><![CDATA[Ivy Ho]]></dc:creator>
            <pubDate>Sat, 11 Jun 2022 08:47:05 GMT</pubDate>
            <atom:updated>2022-06-11T08:47:05.729Z</atom:updated>
            <content:encoded><![CDATA[<h3>[JS30筆記]-Day14 Object and Arrays — Reference VS Copy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPkSYwkdClnZLStSHWTxBQ.png" /></figure><p>今天要學習 JS 中「傳值」或「傳址」的觀念，以及淺層複製、深層複製的方法。</p><h4>學習重點</h4><p><strong>一、字串、數字、布林 皆為傳值</strong></p><p><strong>二、陣列傳址</strong></p><p><strong>三、陣列淺層複製的 4 種方法</strong></p><ol><li>.slice()</li><li>[].concat()</li><li>[… ] 展開運算符</li><li>Array.from()</li></ol><p><strong>四、物件傳址</strong></p><p><strong>五、物件淺層複製的 2 種方法</strong></p><ol><li>Object.assign({}, , )</li><li>{...} 展開運算符</li></ol><p><strong>六、物件深層複製 —</strong><strong> JSON.parse(JSON.stringify())</strong></p><h4><strong>一、字串、數字、布林 皆為傳值</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dypgms0dHdqstMsXTs2QOw.png" /></figure><p>以上範例中，age2 只是將 age 的內容複製一份過來，此時兩者是各自獨立的，就算去改變其中一個變數的值，也不影響另一個。此種傳遞資料的概念即為<strong>「傳值」</strong>。</p><p>除了以上的數字傳值範例，字串和布林也是透過「傳值」的方式，將內容複製到另一個變數，複製後就互不影響。</p><h4><strong>二、陣列傳址</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A5J5yPcig51J9608iToY1Q.png" /></figure><p>players 為一個陣列，此時若讓 team = players，在 JavaScript 中是透過「引用」的方式傳遞資料，會讓兩個變數都指向同一個實體，此種傳遞資料的概念即為<strong>「傳址」</strong>。</p><p>所以當我們修改 team 陣列內的其中一個項目，players 陣列也會跟著改變。</p><h4><strong>三、陣列淺層複製的 4 種方法</strong></h4><p>如果不希望修改陣列的一個項目後，會和另一個陣列互相連動，可以使用淺層複製的方式，將陣列複製成另一個新陣列。分別有以下 4 種方法 :</p><ol><li><strong>.slice()</strong></li></ol><pre>const team2 = players.slice();</pre><p><strong>2. </strong><strong>[].concat()</strong></p><pre>const team2 = [].concat(players);</pre><p><strong>3. </strong><strong>[… ] 展開運算符</strong></p><pre>const team2 = [...players];</pre><p><strong>4. </strong><strong>Array.from()</strong></p><pre>const team2 = Array.from();</pre><h4><strong>四、物件傳址</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uSIKKeiv0CeOX4KtSo0jHQ.png" /></figure><p>物件和陣列一樣，也是以<strong>「傳址」</strong>的方式在傳遞資料。</p><p>所以如以上範例中，用 person2 = person 複製一份的這種做法，一樣會有兩物件互相連動的問題。</p><h4><strong>五、物件淺層複製的 2種方法</strong></h4><ol><li><strong>Object.assign({},)</strong></li></ol><p><strong>複製一個物件 :</strong></p><pre>const person2 = Object.assign({}, person);</pre><p><strong>複製並改變物件內其中一個項目值 :</strong></p><pre>const person2 = Object.assign({}, person, {name: &#39;Wesley&#39;});</pre><p><strong>2. </strong><strong>{...} 展開運算符</strong></p><pre>const person2 = {...person}</pre><p>以上兩種方法雖能將物件複製成另一個新物件，但<strong>當物件有第二層，修改淺層複製過後的第二層內容，依然會影響原物件</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qBi8-DDAzcVwXht9BsRjcQ.png" /></figure><p>以上範例中，修改物件內 name 屬性的值，並不會影響另一個物件。但當我們修改物件內， social 物件裡的 twitter 值，另一個物件內的 twitter 值也會跟著改變。</p><h4><strong>六、物件深層複製 —</strong><strong> JSON.</strong>parse<strong>(JSON.stringify())</strong></h4><p>如果想避免複製物件後，修改第二層的內容仍會與原物件連動，我們可以使用深層複製的方法。</p><p>但影片中有提到，不太推薦這種作法，使用前可以先思考看看是否有其必要性，因為一般很少有需要深層複製一整個物件的情況。</p><p>深層複製的方法，可以參考 lodash 函示庫內，已有的深層複製函式來幫助我們。</p><p>或是使用以下方法，先將物件用 JSON.stringify 轉為 JSON 字串，再用 JSON.parse 轉回原型別 — 物件，來做深層複製 :</p><pre>const person3 = JSON.parse(JSON.stringify(person));</pre><h3>參考資料</h3><ul><li><a href="https://github.com/wesbos/JavaScript30">GitHub - wesbos/JavaScript30: 30 Day Vanilla JS Challenge</a></li><li><a href="https://javascript30.com/">JavaScript 30</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97dd44ef6354" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ivycodefive/js30%E7%AD%86%E8%A8%98-day14-object-and-arrays-reference-vs-copy-97dd44ef6354">[JS30筆記]-Day14 Object and Arrays — Reference VS Copy</a> was originally published in <a href="https://medium.com/ivycodefive">IvyCodeFive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JavaScript 30]Day13-Slide In on Scroll]]></title>
            <link>https://medium.com/ivycodefive/javascript-30-day13-slide-in-on-scroll-7b1c2b83f7a2?source=rss-3691ce586f53------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b1c2b83f7a2</guid>
            <category><![CDATA[學習筆記]]></category>
            <category><![CDATA[js30]]></category>
            <category><![CDATA[前端筆記]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ivy Ho]]></dc:creator>
            <pubDate>Sun, 05 Jun 2022 15:24:59 GMT</pubDate>
            <atom:updated>2022-06-05T15:34:26.836Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPkSYwkdClnZLStSHWTxBQ.png" /></figure><p>今天要練習用純 JS，監聽 scroll 事件、計算高度，以及控制 CSS 樣式，做出類似 <a href="https://michalsnik.github.io/aos/">AOS</a> 套件裡 fade-right、fade-left 的動畫效果!</p><h4>功能需求</h4><ol><li>當頁面滾動到超過圖片高度一半的位置，讓圖片由左或由右淡入顯示。</li><li>由頁面下方往回滾動至上方，也要有一樣的效果。</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H6Y-j_kUgbqgXpK67sB-uA.jpeg" /></figure><h4>學習重點</h4><ul><li>scroll 事件</li><li>debounce 函式</li><li><a href="https://developer.mozilla.org/zh-CN/docs/Web/API/Window/scrollY">window.scrollY</a></li><li><a href="https://developer.mozilla.org/zh-CN/docs/Web/API/Window/innerHeight">window.innerHeight</a> (唯讀屬性)</li><li><a href="https://developer.mozilla.org/zh-CN/docs/Web/API/HTMLElement/offsetTop">.offsetTop</a> (唯讀屬性)</li></ul><h4>觀察範例檔案初始狀態</h4><p><strong>html :</strong></p><p>範例中總共有 5 個圖片進入點，預設有 5 張圖片，都有 .slide-in 這個 class 名稱，搭配 .align-right 或 .align-left</p><p>例如 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQqCo8_QQ-J6qfIDSymFsw.png" /></figure><p><strong>CSS :</strong></p><p>與圖片淡入效果相關的 CSS 都預先寫好了</p><ul><li>利用 float 讓圖片在文章中有文繞圖的效果</li><li>先預設 opacity 為 0，讓圖片先隱藏</li><li>加入 transition 設定，等等控制圖片出現才會有漸變效果</li><li>利用 transform 的 translateX 先將圖片往外位移， 以及 scale 設置，讓圖片小一些。</li><li>之後再利用 JS 判斷條件，加上 .active 這個 class，將 opacity 設回 1，translateX 將圖片拉回原位，scale 讓圖片變回原來大小，就可以達成我們要的淡入動畫效果。</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TGQ6FvW-6CFi8ZXmbI9rAg.png" /></figure><h4>JS :</h4><p>已預先放了一段 debounce 程式碼，常用來防止事件頻繁被觸發。</p><p>在此範例中，可用來避免監聽 scroll event 時，在連續滾動的情況下，頻繁觸發事件，造成頁面效能負擔。</p><p>在第一行 wait=20 的參數位置，可以設定要延遲的毫秒數。</p><pre>function debounce(func, wait = 20, immediate = true) {</pre><pre>  var timeout;</pre><pre>  return function() {</pre><pre>    var context = this, args = arguments;</pre><pre>    var later = function() {</pre><pre>      timeout = null;</pre><pre>      if (!immediate) func.apply(context, args);</pre><pre>    };</pre><pre>    var callNow = immediate &amp;&amp; !timeout;</pre><pre>    clearTimeout(timeout);</pre><pre>    timeout = setTimeout(later, wait);</pre><pre>    if (callNow) func.apply(context, args);</pre><pre>  };</pre><pre>}</pre><p><strong>(最後完成的完整 JS 程式碼，以及檔案下載、課程連結，將放在最下方)</strong></p><h4>解決思路</h4><p>一、對 window 監聽 scroll event，觸發 checkSlide 事件</p><p>二、抓到判斷圖片滑入的基準點</p><p>三、計算出圖片最底部距離頁面最上方的高度值</p><p>四、判斷如果符合條件，就在圖片加上 .active 這個 class 以達到淡入動畫效果</p><h4>一、對 window 監聽 scroll event，觸發 checkSlide 事件</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E1hoO_BlW80q3U-2Sh_fuA.png" /></figure><ul><li>為了防止事件被頻繁觸發，影響頁面效能，所以將事件利用 debounce 函式做處理。</li></ul><h4>二、抓到判斷圖片滑入的基準點</h4><p>抓到當前視窗最底位置的高度值(依滾動的情況不同，此高度值會動態變化)，減去圖片高度的一半</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VM2fHuIv05vX1DKSe0LfHQ.png" /></figure><ul><li>遍歷每一張圖片</li><li>當前視窗最底位置的高度值 = window.scrollY(已捲動的高度) + window.innerHeight(視窗高度)</li><li>圖片高度的一半 = sliderImage.height / 2</li><li>slideInAt = 當前頁面最底位置的高度值 - 圖片高度的一半</li></ul><h4>三、計算出圖片最底部距離頁面最上方的高度值</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bLNzD0EwVT-Ihd44Lu2GAA.png" /></figure><ul><li>利用 sliderImage.offsetTop (圖片距離頁面最上方的高度)，加上 sliderImage.height (圖片本身高度)，來獲得圖片最底部距離頁面最上方的高度值 imageBottom</li></ul><h4>四、判斷如果符合條件，就在圖片加上 .active 這個 class 以達到淡入動畫效果</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r2EAqZwWxr7x3IB1H_EAIQ.png" /></figure><ul><li>將判斷條件先存取至變數如 isHalfShown、isNotScrolledPast，可增加程式碼的可讀性，避免判斷式過長，難以閱讀。</li><li>isHalfShown : 當剛剛設定的滑入基準點 slideInAt 高度值，大於圖片距離頁面最上方的高度距離(此時正是頁面滾動到超過圖片高度一半的位置)</li><li>isNotScrolledPast : 圖片最底部還沒消失在視窗畫面</li><li>同時符合以上兩個條件，就在該圖片加上 .active 這個 class ，不符合則移除 .active 。</li></ul><p>到這邊就完成了今天要練習的圖片淡入效果~</p><h4>完整 JS 程式碼</h4><pre>const sliderImages = document.querySelectorAll(&#39;.slide-in&#39;);</pre><pre>function checkSlide(e) {</pre><pre>  sliderImages.forEach(sliderImage =&gt; {</pre><pre>    const slideInAt = (window.scrollY + window.innerHeight) - sliderImage.height / 2;</pre><pre>    const imageBottom = sliderImage.offsetTop + sliderImage.height;</pre><pre>    const isHalfShown = slideInAt &gt; sliderImage.offsetTop;</pre><pre>    const isNotScrolledPast = window.scrollY &lt; imageBottom;</pre><pre>    if(isHalfShown &amp;&amp; isNotScrolledPast) {</pre><pre>      sliderImage.classList.add(&#39;active&#39;);</pre><pre>    }else {</pre><pre>      sliderImage.classList.remove(&#39;active&#39;);</pre><pre>    }</pre><pre>  })</pre><pre>}</pre><pre>window.addEventListener(&#39;scroll&#39;, debounce(checkSlide));</pre><h4>參考資料</h4><ul><li><a href="https://github.com/wesbos/JavaScript30">GitHub - wesbos/JavaScript30: 30 Day Vanilla JS Challenge</a></li><li><a href="https://javascript30.com/">JavaScript 30</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b1c2b83f7a2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ivycodefive/javascript-30-day13-slide-in-on-scroll-7b1c2b83f7a2">[JavaScript 30]Day13-Slide In on Scroll</a> was originally published in <a href="https://medium.com/ivycodefive">IvyCodeFive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[[JS30筆記]-Day12 Key Sequence Detection (KONAMI CODE)]]></title>
            <link>https://medium.com/ivycodefive/js30%E7%AD%86%E8%A8%98-day12-key-sequence-detection-konami-code-dac329fe006c?source=rss-3691ce586f53------2</link>
            <guid isPermaLink="false">https://medium.com/p/dac329fe006c</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[學習筆記]]></category>
            <category><![CDATA[前端筆記]]></category>
            <category><![CDATA[js30]]></category>
            <dc:creator><![CDATA[Ivy Ho]]></dc:creator>
            <pubDate>Sat, 28 May 2022 07:23:17 GMT</pubDate>
            <atom:updated>2022-05-28T07:23:17.087Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fPkSYwkdClnZLStSHWTxBQ.png" /></figure><p>今天要練習偵測、驗證鍵盤輸入內容序列。也能學會如何埋彩蛋在網頁上，讓使用者<strong>輸入秘密指令後，看到驚喜的畫面</strong>。👾👀</p><p>說到 KONAMI CODE (↑↑↓↓←→←→BA START)這個東西，大家應該都不陌生，連從小沒在打電動的我，都有聽過這串指令。</p><p>剛剛去搜尋了它的由來，覺得十分有趣，原來一開始是不小心的啊~</p><p><a href="https://ccc.technews.tw/2020/02/27/konami-code-maker-kazuhisa-hashimoto-passed-away/">「上上下下左右左右ＢＡ」Konami Code 的創造者，遊戲設計師橋本和久過世</a></p><p>後來有很多網頁也會採用這段指令，在網頁上做一些小彩蛋給使用者驚喜。</p><p>目前能找到的例子有 <a href="https://www.goskills.com/">go skills</a> 這個網站，只要輸入 ↑↑↓↓←→←→BA，就會跳出這個小精靈遊戲，破關即有機會獲得優惠券。</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7V8NuiWHG7u-qB9yUZ6AFg.png" /></figure><p>今天要練習的範例是將秘密指令設定為一串字串。</p><p>想了解該如何偵測到使用者在瀏覽器開啟網頁後，輸入了秘密指令，就讓我們繼續看下去~</p><h4>學習重點</h4><ul><li>e.key</li><li>.splice()</li><li>.join(&#39;&#39;)</li><li>.includes()</li></ul><h4>觀察範例檔案初始狀態</h4><p>範例檔案中沒有 html 前端介面，只有預先載入一支 cornify.js，等等就能知道它的用途了~ 🦄🌈</p><pre>&lt;script type=&quot;text/javascript&quot; src=&quot;https://www.cornify.com/js/cornify.js&quot;&gt;&lt;/script&gt;</pre><h4>解決思路</h4><p>一、預設秘密指令內容，並偵測使用者輸入的字串內容</p><p>二、處理使用者輸入的字串陣列長度，以方便下一步比對</p><p>三、比對使用者輸入的字串是否與預設的秘密指令相符</p><h4>一、預設秘密指令內容，並偵測使用者輸入的字串內容</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xi5SG-Bpyy_olTx3uvO_Sw.png" /></figure><ul><li>預設秘密指令為 ‘wesbos’</li><li>對 window 監聽 keyup event，可以利用 e.key 取得使用者按下按鍵的值</li><li>再將它們 push 到預設的空陣列 pressed 裡面</li><li>console.log(pressed) 就能看到輸入的值所組成的陣列 :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*awDCcupeZC8lf4atOTwzyA.png" /></figure><h4>二、處理使用者輸入的字串陣列長度，以方便下一步比對</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3e-W1U8thihR1XnN5spGGA.png" /></figure><p><strong>此步驟利用 </strong><strong>.splice 做了兩件事 :</strong></p><ol><li>控制陣列內的字數，保持不超過 secretCode 長度的字數</li><li>當字數多於 secretCode 長度，新輸入的字會從最後面新增，最前面的字則會被刪除</li></ol><p>在字串陣列還沒用 .splice 處理之前，陣列的長度會像這樣無限增加 :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*BZETalS57_Jfsbt-_iks3w.png" /></figure><p>為了方便進一步比對，我們需要先將它用 .splice 方法進行處理。</p><p><a href="https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Array/splice"><strong>.splice()</strong></a><strong> 方法 : </strong>可以藉由刪除既有元素並／或加入新元素來改變一個陣列的內容。</p><pre>.splice(要插入或刪除的索引位置, 要刪除的元素數量, 要插入的元素內容)</pre><p>我們只需要使用它的刪除功能，所以只會用到前兩個參數。</p><pre>pressed.spliced(-secretCode.length -1, pressed.length - secretCode.length);</pre><p>第二個參數為「要刪除的元素數量」，所以是利用 pressed 長度減去 secretCode 長度，得到多於的數量，就是我們要刪除的，這部分較好理解。</p><p>但第一個參數「要插入或刪除的索引位置」 帶入<strong> </strong>-secretCode.length -1</p><p>讓我花最多時間理解。</p><p>參考了他人的筆記 :</p><p>「演算法設置 : 由於start為負數時會從最後一個開始算起的下一個計算，所以當start為-1時，起始位置是最後一個的下一個，此時不會有資料被刪除，當起始位置為 -2 時才會刪除最後一個；同理若要刪除第一個時，則要設置為-n -1。」</p><p>來源 :</p><p><a href="https://github.com/dustinhsiao21/Javascript30-dustin/tree/master/12%20-%20Key%20Sequence%20Detection">Javascript30-dustin/12 - Key Sequence Detection at master · dustinhsiao21/Javascript30-dustin</a></p><p>但如果已知要從第一項開始刪除，是否直接帶入 0 也可以呢?</p><p>帶入 -n-1 是否可以避免什麼樣的情況?</p><p>或許是因為我對演算法還不夠了解，希望日後能漸漸體會這個 -n-1 的奧秘😅</p><p>經過 .splice() 的處裡後，陣列就會維持在不超過一定字數的長度，超過的話，每新增一個，第一個就會被移除~</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1020/1*sXdL7YTpbblQvRTh7w30Gg.png" /></figure><p>再加上下面第三步驟做比對，我們就能在偵測到使用者輸入完整指令時(紅色打勾處)，觸發其他驚喜事件囉~</p><h4>三、比對使用者輸入的字串是否與預設的秘密指令相符</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vfRDC4PRqo1VyMAzXWZ5_Q.png" /></figure><ul><li>利用 join(&#39;&#39;) 來將陣列內一個個字，合併成一個完整字串</li><li>再利用 includes() 來比對字串是否與 secretCode 相符</li><li>比對結果為 true 的話，就可以在這邊觸發要給使用者的驚喜</li><li>範例中，因為剛開始有載入一支 cornify.js，我們可以在比對結果為 true 之後觸發 cornify_add() 這個事件，只要每輸入一次 secretCode，畫面上就會多出一個閃亮亮的獨角獸或彩虹圖案🤗哈哈哈</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/845/1*2-1yAUbJBcp47O_s_5LAAg.png" /></figure><p>今天的練習就到這邊結束囉~</p><h4>完整 JS 程式碼</h4><pre>const pressed = [];</pre><pre>const secretCode = &#39;wesbos&#39;;</pre><pre>window.addEventListener(&#39;keyup&#39;, (e) =&gt; {</pre><pre>  pressed.push(e.key);</pre><pre>  pressed.splice(-secretCode.length - 1, pressed.length -   secretCode.length);</pre><pre>  if (pressed.join(&#39;&#39;).includes(secretCode)) {</pre><pre>    cornify_add();</pre><pre>  }</pre><pre>});</pre><h4>參考資料</h4><ul><li><a href="https://github.com/wesbos/JavaScript30">GitHub - wesbos/JavaScript30: 30 Day Vanilla JS Challenge</a></li><li><a href="https://javascript30.com/">JavaScript 30</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dac329fe006c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ivycodefive/js30%E7%AD%86%E8%A8%98-day12-key-sequence-detection-konami-code-dac329fe006c">[JS30筆記]-Day12 Key Sequence Detection (KONAMI CODE)</a> was originally published in <a href="https://medium.com/ivycodefive">IvyCodeFive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>