js实现鼠标动画事件

基本原理:创建div 当鼠标选中不同的菜单选项时,给li添加一个类名以获取当前选择的li标签的宽度和该元素离ul的距离,再设置给该div;

其中js用到:

obj.offsetLeft:obj对象与相对于父对象的左边距

obj.offsetWidth:obj对象的盒子宽度

html结构

 

css


        .head {
            width: 100%;
            height: 1080px;
        }

        .head img {
            object-fit: cover;
            width: 100%;
            height: 100%;
        }

        .menu {
            width: 100%;
            height: 50px;

        }

        .menu-ul {
            position: relative;
            width: 500px;
            margin: auto;
        }

        .menu-ul>ul {
            width: 100%;
            line-height: 50px;

            display: flex;
            justify-content: space-between;
        }

        .menu-ul>ul li {
            z-index: 2;
            list-style-type: none;
            cursor: pointer;
        }

        .conter {
            width: 100%;
            height: 1500px;
            background: rgb(56, 48, 39);

        }

        .fixed {
            position: fixed;
            top: 0;
            left: 0;
            color: white;
        }

        .nav-menu {
            width: 64px;
            height: 30px;
            background: #f60;
            border-radius: 20px;
            position: absolute;
            margin-top: 4px;
            left: 0;
            top: 5px;
            transition: all .3s;
            padding: 0 0 0 30px;
          
        }

js初始化默认选择样式实现部分:

function $(id) {
            return document.getElementById(id);
        }
        //获取菜单
        var menuul = document.getElementsByClassName("nav-menu")[0];
        var menyuulleft = 0;
        var menuwidth = 0;
        //初始化选中
        var lists = document.getElementsByTagName("li");
        var navchecked = document.getElementsByClassName("curr")[0];
        var navcheckleft = navchecked.offsetLeft;
        var navcheckwidth = navchecked.offsetWidth;
        // console.log(navcheckleft);
        // console.log(navcheckwidth);
        //定义选择状态方法
        function infomenu() {
            menuul.style.left = navcheckleft-15 + "px";
            menuul.style.width = navcheckwidth + "px";
            navchecked.classList.add("curr");
        }
        infomenu();

鼠标移动选中动画

 //创建li监听
         for (let i = 0; i

 

你可能感兴趣的:(javaScript基础)