GitHub前端50天50個(gè)項(xiàng)目,第4個(gè) 隱藏搜索小部件

演示地址

Hidden Search (50projects50days.com)

實(shí)現(xiàn)思路

先把搜索框和搜索按鈕盒子大小設(shè)置成一樣,搜索按鈕絕對(duì)定位蓋住搜索框。點(diǎn)擊搜索按鈕時(shí)展開搜索框,同時(shí)利用transform將搜索按鈕從搜索框上面移開。

代碼

html結(jié)構(gòu)

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>隱藏搜索小部件</title>
    <link  rel="stylesheet">
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="search">
        <input type="text" class="input" name="" placeholder="Search...">
        <button class="btn">
            <i class="fas fa-search"></i>
        </button>
    </div>
    <script src="./script.js"></script>
</body>

</html>

css樣式

* {
    box-sizing: border-box;
}

body {
    /* 彈性布局,垂直居中 */
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
    background-color: pink;
    overflow: hidden;
}

.search {
    /* 父元素相對(duì)定位 */
    position: relative;
    height: 50px;
}

.search .input {
    padding: 15px;
    height: 50px;
    width: 50px;
    border: 0;
    background-color: #fff;
    font-size: 18px;
    transition: width 0.3s ease;
}

.btn {
    cursor: pointer;
    /* 絕對(duì)定位 */
    position: absolute;
    top: 0;
    left: 0;
    width: 50px;
    height: 50px;
    border: 0;
    background-color: #fff;
    font-size: 24px;
    transition: transform 0.3s ease;
}

.btn:focus,
.input:focus {
    outline: none;
}

.search.active .input {
    width: 200px;
}

.search.active .btn {
    transform: translateX(200px);
}

js行為

const search = document.querySelector('.search')
const btn = document.querySelector('.btn')
const input = document.querySelector('.input')

btn.addEventListener('click', () => {
    // toggle() 方法從列表中刪除一個(gè)給定的標(biāo)記并返回false。 如果標(biāo)記不存在,則添加標(biāo)記并且函數(shù)返回true
    search.classList.toggle('active')
    input.focus()
})

參考資料:50 Projects 50 Days | Traversy Media
50 unique mini-projects to sharpen your HTML, CSS & JavaScript skills

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容