1 問(wèn)題描述 在制作網(wǎng)頁(yè)時(shí),若想讓頂部的導(dǎo)航欄在頁(yè)面整體滑動(dòng)時(shí),導(dǎo)航欄一直在頂部顯示。 準(zhǔn)備:引入element組件。 2 算法描述 使用addEventListener() 方法,進(jìn)行事件監(jiān)聽(tīng),用于向指定元素添加事件句柄。 element.addEventListener(event, function, useCapture) 第一個(gè)參數(shù)是事件的類型 (如 "click" 或 "mousedown"); 注意:必須。字符串,指定事件名。不要使用 "on" 前綴。例如,使用 "click" ,而不是使用 "onclick"。 第二個(gè)參數(shù)是事件觸發(fā)后調(diào)用的函數(shù); 第三個(gè)參數(shù)是個(gè)布爾值用于描述事件是冒泡還是捕獲。該參數(shù)是可選的。 具體看代碼注釋。 (一)template 代碼清單 1 <template> <!-- 導(dǎo)航 --> <div class="Head "> <div class="navtop"> <img class="top_picture" src="./assets/9.jpg"> <el-button type="text" class="navbar">觀光&活動(dòng)</el-button> <el-button type="text" class="navbar">計(jì)劃您的旅程</el-button> <el-button type="text" class="navbar navbar_1">旅游必備信息</el-button> </div> <div class="navend"> <el-button type="text" size="small"><i class="el-icon-search" style="color: black;margin-top: 12px;"><span> |</span></i></el-button> <el-button round size="small" style="background:rgba(218, 218, 218, 0.3);border:0px; "> 申請(qǐng)電子簽證 </el-button> <el-button round size="small" type="success" round> 注冊(cè)</el-button> </div> </div> </template> |
SCRIPT樣式 代碼清單 2 <script> import { videoPlayer } from 'vue-video-player' export default { name: 'VideoPlayer', } window.addEventListener('scroll', function() { /* 獲取文檔中 class="Head" 的元素:*/ let tou = document.querySelector('.Head'); /* tou.classList.toggle("bian",window.scrollY>0); */ /* 使用此scrollY屬性來(lái)檢查使用相對(duì)滾動(dòng)函數(shù)(例如,scrollBy(),scrollByLines()或scrollByPages())時(shí)文檔是否已滾動(dòng)。*/ if (window.scrollY > 0) { // classListAPI提供了原生的方式來(lái)添加,刪除,切換,或檢查CSS類存在的元素
/* classList.add() 添加類名 */ tou.classList.add("bian"); /* bian 為導(dǎo)航欄滑動(dòng)時(shí)設(shè)置的類名 */ } else { tou.classList.remove("bian"); } }) </script> |
CSS樣式 代碼清單 3 <style> /* 導(dǎo)航欄 */ .Head { width: 100%; height: 50px; position: fixed; top: 0; left: 0; right: 0; justify-content: space-between; align-items: center; transition: 0.5s; display: flex; z-index: 3; } .navtop { width: 70%; float: left; } .navend { width: 30%; float: right; } .top_picture { position: relative; width: 30px; height: 30px; padding-left: 20px; padding-top: 10px; } /* 導(dǎo)航欄 滑動(dòng)時(shí)的樣式設(shè)置*/ .bian { background-color: rgb(255, 255, 255); } .bian .Head { color: rgb(0, 0, 0); } .navbar { margin-left: 10px; padding-right: 30px; margin-top: 2px; color: #000000; } .el-button:hover { color: #e9e9e9; } </style> |
具體效果: 
3 結(jié)語(yǔ) 本篇文章主要講的是通過(guò)添加addEventListener()方法來(lái)對(duì)導(dǎo)航欄滑動(dòng)時(shí)進(jìn)行樣式的設(shè)置。在本次實(shí)驗(yàn)中的圖片未能很好的使其進(jìn)行居中。本篇文章并未完全講完關(guān)于addEventListener()方法的參數(shù),但可以通過(guò)教程查看其他消息,同時(shí)若想移除 addEventListener() 方法添加的事件句柄則使用 removeEventListener() 方法來(lái)移除。 實(shí)習(xí)編輯:衡輝 稿件來(lái)源:深度學(xué)習(xí)與文旅應(yīng)用實(shí)驗(yàn)室(DLETA)
|