前端每日實戰:162# 視頻演示如何用原生 JS 創做一個查詢 github 用戶的應用(內含 2 個視頻)

圖片描述

效果預覽

按下右側的「點擊預覽」按鈕能夠在當前頁面預覽,點擊連接能夠全屏預覽。javascript

https://codepen.io/comehope/pen/oQGqaGcss

可交互視頻

此視頻是能夠交互的,你能夠隨時暫停視頻,編輯視頻中的代碼。html

請用 chrome, safari, edge 打開觀看。前端

第 1 部分:
https://scrimba.com/p/pEgDAM/cEPkVUgjava

第 2 部分:
https://scrimba.com/p/pEgDAM/crp63TRgit

(由於 scrimba 不支持 web animation api,第 2 部分末尾的動畫效果在視頻中看不到,請參考 codepen)github

源代碼下載

每日前端實戰系列的所有源代碼請從 github 下載:web

https://github.com/comehope/front-end-daily-challengeschrome

代碼解讀

這是一個讀取 github 用戶的應用,在搜索框內輸入用戶名,點擊搜索後,就會經過 github 的 open api 取得用戶信息,填寫到下方的卡片中。json

整個應用分紅 3 個步驟開發:靜態的頁面佈局、從 open api 讀取數據並綁定到頁面中、增長動畫效果。

1、頁面佈局

定義 dom,總體結構分紅上部的表單和下部的用戶卡片:

<div class="app">
    <form>
        <!-- 暫略 -->
    </form>
    <div class="profile">
        <!-- 暫略 -->
    </div>
</div>

居中顯示:

body {
    margin: 0;
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
    background-color: #383838;
}

定義應用容器的尺寸:

.app {
    width: 320px;
    height: 630px;
    font-family: sans-serif;
    position: relative;
}

這是表單的 dom 結構,2 個表單控件分別是文本輸入框 #username 和搜索按鈕 #search,由於後面的腳本要引用這 2 個控件,因此爲它們定義了 id 屬性,接下來在 css 中也使用 id 選擇器:

<form>
    <input placeholder="Who are you looking for?" id="username">
    <input type="button" value="Search" id="search">
</form>

令 2 個表單控件橫向排列:

form {
    height: 50px;
    background-color: rgba(255, 255, 255, 0.2);
    border-radius: 2px;
    box-sizing: border-box;
    padding: 8px;
    display: flex;
}

分別設置 2 個表單控件的樣式:

input {
    border: none;
    font-size: 14px;
    outline: none;
    border-radius: inherit;
    padding: 0 8px;
}
  
#username {
    flex-grow: 1;
    background-color: rgba(255, 255, 255, 0.9);
    color: #42454e;
}
  
#search {
    background-color: rgba(0, 97, 145, 0.75);
    color: rgba(255, 255, 255, 0.8);
    font-weight: bold;
    margin-left: 8px;
    cursor: pointer;
}

爲按鈕增長懸停和點擊的交互效果:

#search:hover {
    background-color: rgba(0, 97, 145, 0.45);
}

#search:active {
    transform: scale(0.98);
    background-color: rgba(0, 97, 145, 0.75);
}

至此,表單佈局完成,接下來作用戶卡片佈局。
用戶卡片的 dom 結構以下,卡片分紅上半部分 .header 和下半部分 .footer,上半部分包括頭像 .avatar、名字 .name 和位置 .location,下半部分包括一組詳細的數據 .details 和一個跳到 github 的連接 .to-github

<div class="profile">
    <div class="header">
        <div class="avatar"></div>
        <h2 class="name">Octocat</h2>
        <h3 class="location">San Francisco</h3>
    </div>
    <div class="footer">
        <ul class="details">
            <li>Repositories<span>111</span></li>
            <li>Followers<br><span>222</span></li>
            <li>Following<br><span>333</span></li>
        </ul>
        <a href="#" class="to-github">go to github</a>
    </div>
</div>

令卡片的上半部分和下半部分豎向排列,並分別設置兩部分的高度,大約是上半部分佔卡片高度的三分之二,下半部分佔卡片高度的三分之一,此時能夠看出卡片的輪廓了:

.profile {
    width: 320px;
    position: absolute;
    margin: 20px 0 0 0;
    display: flex;
    flex-direction: column;
    border-radius: 5px;
}

.header {
    height: 380px;
    background-color: rgba(0, 97, 145, 0.45);
}

.footer {
    height: 180px;
    background-color: rgba(0, 97, 145, 0.75);
}

令卡片上半部分的子元素豎向排列:

.header {
    display: flex;
    flex-direction: column;
    align-items: center;
}

設置頭像圖片,樣式爲描邊的圓形,由於頭像圖片在後面還會用到,因此把它存儲到變量 --avatar 中:

.profile {
    --avatar: url('https://avatars3.githubusercontent.com/u/583231?v=4');
}

.avatar {
    width: 140px;
    height: 140px;
    background-image: var(--avatar);
    margin: 70px 0 0 0;
    background-position: center;
    background-size: cover;
    border-radius: 50%;
    box-shadow: 
        0 0 0 0.8em rgba(0, 0, 0, 0.2),
        0 0 0 1em rgba(161, 220, 255, 0.35);
}

設置名字和位置信息的樣式,文字爲白色:

.name {
    margin: 50px 0 0 0;
    color: white;
    font-size: 28px;
    font-weight: normal;
    text-shadow: 0 1px 2px rgba(0, 0, 0, 0.15);
}

.location {
    margin: 5px 0 0 0;
    color: rgba(255, 255, 255, 0.75);
    font-weight: normal;
}

至此,上半部分的佈局完成,接下來佈局下半部分。
令下半部分的子元素豎向排列:

.footer {
    display: flex;
    flex-direction: column;
    align-items: center;
}

橫向排列三組數據,每項之間加入細分隔線:

.details {
    list-style-type: none;
    padding: 0;
    display: flex;
    margin: 40px 0 0 0;
}

.details li {
    color: rgba(255, 255, 255, 0.6);
    text-align: center;
    padding: 0 6px;
}

.details li span {
    display: block;
    color: rgba(255, 255, 255, 0.8);
}

.details li:not(:first-child) {
    border-left: 2px solid rgba(255, 255, 255, 0.15);
}

設置跳轉到 github 的連接樣式和懸停效果:

.to-github {
    width: 200px;
    height: 40px;
    background-color: rgba(255, 255, 255, 0.5);
    text-align: center;
    line-height: 40px;
    color: rgba(0, 0, 0, 0.75);
    text-decoration: none;
    text-transform: uppercase;
    border-radius: 20px;
    transition: 0.3s;
}

.to-github:hover {
    background-color: rgba(255, 255, 255, 0.8);
}

至此,下半部分佈局完成。
接下來用僞元素把頭像圖片做爲總體背景:

.profile {
    position: relative;
    overflow: hidden;
}

.profile::before {
    content: '';
    position: absolute;
    width: calc(100% + 20px * 2);
    height: calc(100% + 20px * 2);
    background-image: var(--avatar);
    background-size: cover;
    z-index: -1;
    margin: -20px;
    filter: blur(10px);
}

到這裏,總體的靜態佈局就完成了。

2、綁定數據

爲了綁定數據,咱們引入一個羽量級的模板庫:

<script src="https://blueimp.github.io/JavaScript-Templates/js/tmpl.min.js"></script>

把卡片 .profile 包含的 dom 結構改寫爲 html 模板 #template,其中的 o 表明綁定的數據數據對象:

<script type="text/x-tmpl" id="template">
    <div class="header">
        <div class="avatar"></div>
        <h2 class="name">{%= o.name %}</h2>
        <h3 class="location">{%= o.location %}</h3>
    </div>
    <div class="footer">
        <ul class="details">
            <li>Repositories<span>{%= o.public_repos %}</span></li>
            <li>Followers<br><span>{%= o.followers %}</span></li>
            <li>Following<br><span>{%= o.following %}</span></li>
        </ul>
        <a href="{%= o.html_url %}" class="to-github">go to github</a>
    </div>
</script>

聲明一個假數據對象 mockData,它的數據結構與 github open api 的數據結構是一致的:

let mockData = {
    "avatar_url": "https://avatars3.githubusercontent.com/u/583231?v=4",
    "name": "The Octocat",
    "location": "San Francisco",
    "public_repos": 111,
    "followers": 222,
    "following": 333,
    "html_url": "https://github.com/octocat",
}

定義一個把數據綁定到 html 模板的函數 render(container, data),第 1 個參數 container 表示 dom 容器,模板內容將填充在此容器中;第 2 個參數是數據對象。在頁面載入時調用 render() 方法,把 mockData 做爲參數傳入,此時看到的效果和純靜態的效果一致,但用戶卡片已經改成動態建立了:

window.onload = render(document.getElementsByClassName('profile')[0], mockData)

function render(container, data) {
    container.innerHTML = tmpl('template', data)
    container.style.setProperty('--avatar', `url(${data.avatar_url})`)
}

定義一個從 github open api 讀取用戶信息的方法 getData(username),而後調用 render() 方法把用戶信息綁定到 html 模板。同時,把 window.onload 綁定的事件改成調用 getData() 方法,此時看到的效果仍和純靜態的效果一致,但數據已經變成動態讀取了:

window.onload = getData('octocat')

function getData(username) {
    let apiUrl = `https://api.github.com/users/${username}`
    fetch(apiUrl)
        .then((response) => response.json())
        .then((data) => render(document.getElementsByClassName('profile')[0], data))
}

爲表單的 search 按鈕綁定點擊事件,實現搜索功能。能夠查一下本身的 github 賬號試試看:

document.getElementById('search').addEventListener('click', () => {
    let username = document.getElementById('username').value.replace(/[ ]/g, '')
    if (username == '') {
        return
    }
    getData(username)
})

3、增長動畫效果

爲了能讓用戶感覺到每次搜索後數據的變化過程,咱們增長一點動畫效果。建立一個 update(data) 函數來處理動畫和渲染邏輯,同時把 getData() 函數的最後一步改成調用 update() 函數:

function getData(username) {
    let apiUrl = `https://api.github.com/users/${username}`
    fetch(apiUrl)
        .then((response) => response.json())
        // .then((data) => render(document.getElementsByClassName('profile')[0], data))
        .then(update)
}

function update(data) {
    let current = document.getElementsByClassName('profile')[0]
    render(current, data)
}

當頁面首次載入時,不須要動畫,直接渲染默認的用戶信息便可。變量 isInitial 表示本次調用是不是在初始化頁面時調用的,如果,就直接渲染。若不是,下面會執行動畫效果。

function update(data) {
    let current = document.getElementsByClassName('profile')[0]
    let isInitial = (current.innerHTML == '')

    if (isInitial) {
        render(current, data)
        return
    }
}

動畫的過程是:建立一張新卡片,把數據綁定到新卡片上,而後把當前卡片移出視圖,再把新卡片移入視圖。下面的變量 next 表明新建立的卡片,把它定位到當前卡片的右側:

function update(data) {
    let current = document.getElementsByClassName('profile')[0]
    let isInitial = (current.innerHTML == '')

    if (isInitial) {
        render(current, data)
        return
    }

    let next = document.createElement('div')
    next.className = 'profile'
    next.style.left = '100%'
    render(next, data)
    current.after(next)
}

由於動畫分紅 2 個動做——當前卡片移出和新卡片移入,因此咱們定義 2 個動畫效果,變量 animationOut 表明移出動畫的參數,變量 animationIn 表明移入動畫的參數。其中,keyframes 屬性值至關於寫 css 動畫時用 @keyframes 定義的關鍵幀,options 屬性值至關於寫 css 動畫時 animation 語句後面的參數,新卡片移入動畫有半秒鐘的延時。

function update(data) {
    let current = document.getElementsByClassName('profile')[0]
    let isInitial = (current.innerHTML == '')

    if (isInitial) {
        render(current, data)
        return
    }

    let next = document.createElement('div')
    next.className = 'profile'
    next.style.left = '100%'
    render(next, data)
    current.after(next)

    let animationOut = {
        keyframes: [
            {left: '0', opacity: 1, offset: 0},
            {left: '-100%', opacity: 0, offset: 1}
        ],
        options: {
            duration: 500,
            fill: 'forwards'
        }
    }

    let animationIn = {
        keyframes: [
            {left: '100%', opacity: 0, offset: 0},
            {left: '0', opacity: 1, offset: 1}
        ],
        options: {
            duration: 500,
            fill: 'forwards',
            delay: 500
        }
    }
}

由於動畫需異步執行,即在當前卡片移出的動畫結束後再執行新卡片移入的動畫,因此咱們令當前卡片移出的動畫結束後觸發 onfinish 事件,而後再執行新卡片移入的動畫,同時把舊卡片刪除掉:

function update(data) {
    let current = document.getElementsByClassName('profile')[0]
    let isInitial = (current.innerHTML == '')

    if (isInitial) {
        render(current, data)
        return
    }

    let next = document.createElement('div')
    next.className = 'profile'
    next.style.left = '100%'
    render(next, data)
    current.after(next)

    let animationOut = {
        keyframes: [
            {left: '0', opacity: 1, offset: 0},
            {left: '-100%', opacity: 0, offset: 1}
        ],
        options: {
            duration: 500,
            fill: 'forwards'
        }
    }

    let animationIn = {
        keyframes: [
            {left: '100%', opacity: 0, offset: 0},
            {left: '0', opacity: 1, offset: 1}
        ],
        options: {
            duration: 500,
            fill: 'forwards',
            delay: 500
        }
    }

    let animate = current.animate(animationOut.keyframes, animationOut.options)
    animate.onfinish = function() {
        current.remove()
        next.animate(animationIn.keyframes, animationIn.options)
    }
}

最後,限定動畫效果僅在 .app 容器中展示:

.app {
    overflow: hidden;
}

大功告成!

相關文章
相關標籤/搜索