JS實現百度新聞導航欄效果
阿新 • • 發佈:2021-10-27
本文例項為大家分享了實現百度新聞導航欄效果的具體程式碼,供大家參考,具體內容如下
最近在學Web前端,用js簡單實現了百度新聞導航欄的效果。當滑鼠移動到某一選項上方時,會有一個紅色背景塊滑動到當前選項上。當點選某一選項後,固定的紅色背景塊位置會移動到當前選項,意為當前選項被選中。話不多說,程式碼如下
body部分
<div class="box"> <!--兩個紅色背景塊--> <!--隨滑鼠移動的背景塊--> <div id="move"></div> <!--滑鼠點選後固定在某處的背景塊--> <div id="fixed"></div> <a href="#">主頁</a> <a href="#">國內</a> <a href="#">國際</a> <a href="#">軍事</a> <a href="#">財經</a> <a href="#">娛樂</a> <a href="#">體育</a> <a href="#">網際網路</a> <a href="#">科技</a> <a href="#">遊戲</a> <a href="#">女人</a> <a href="#">汽車</a> <a href="#">房產</a> </div>
部分
*{ margin: 0; padding: 0; } .box{ top:100px; width: 790px; height: 30px; font-size: 0; position: relative; margin: 0 auto; background-color: #01204f; www.cppcns.com } a{ display: inline-block; position: relative; width: 60px; height: 30px; line-height: 30px; color: white; http://www.cppcns.comfont-size: 16px; text-decoration: none; text-align: center; transition: all 0.6s; } #move{ position: absolute; background-color: red; top: 0px; left: 0px; width: 60px; height: 30px; transition: all 0.6s; } #fixed{ position: absolute; background-color: red; top: 0px; left: 0px; width: 60px; height: 30px; }
js部分
window.onload = function () {
let move = document.getElementById("move");//滑動的背景塊
let fixed = document.getElementById("fixed");//固定在某處的背景塊
let aList = document.getElementsByTagName("a");//a標籤列表
let left = move.offsetLeft + "px";//滑動背景塊的初始位置
//使所有a標籤繫結移入、移出、單擊事件
for (let i = 0; i < aList.length; i++) {
aList[i].onmouseover = function () {
// 滑鼠移入某個a標籤時,滑動背景塊滑到當前a標籤的位置
move.style.left = aList[i].offsetLeft + "px";
}
aList[i].onmouseout = function () {
// 滑鼠移出a標籤時,滑動背景塊返回初始位置
move.style.left = left;
}
wuNNHL aList[i].onclick = function () {
// 某個a標籤被點選後,固定背景塊移動到當前a標籤的位置
fixed.style.left = aList[i].offsetLeft + "px";
// 將滑動背景塊的初始位置更新為當前a標籤的位置
left = aList[i].offsetLeft + "px";
}
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。