JS实现百度新闻导航栏效果

本文实例为大家分享了JS实现百度新闻导航栏效果的具体代码,供大家参考,具体内容如下

最近在学Web前端,用js简单实现了百度新闻导航栏的效果。当鼠标移动到某一选项上方时,会有一个红色背景块滑动到当前选项上。当点击某一选项后,固定的红色背景块位置会移动到当前选项,意为当前选项被选中。话不多说,代码如下

body部分

css部分

 *{
            margin: 0;
            padding: 0;
        }
        .box{
            top:100px;
            width: 790px;
            height: 30px;
            font-size: 0;
            position: relative;
            margin: 0 auto;
            background-color: #01204f;
        }
        a{
            display: inline-block;
            position: relative;
            width: 60px;
            height: 30px;
            line-height: 30px;
            color: white;
            font-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;
                }
                aList[i].onclick = function () {
                    // 某个a标签被点击后,固定背景块移动到当前a标签的位置
                    fixed.style.left = aList[i].offsetLeft + "px";
                    // 将滑动背景块的初始位置更新为当前a标签的位置
                    left = aList[i].offsetLeft + "px";
                }
            }
        }

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(JS实现百度新闻导航栏效果)