js 鼠标经过和经过离开 导航实战案例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        a {
            float: left;
            width: 80px;
            height: 50px;
            background-color: orangered;
            margin-left: 5px;
            text-decoration: none;
            line-height: 50px;
            text-align: center;
            color: #fff;
        }
    </style>
</head>
<body>
    <a href="javascript:;">导航一</a>
    <a href="javascript:;">导航二</a>
    <a href="javascript:;">导航三</a>
    
    <script>
        var a = document.querySelectorAll('a')

        //用js 代替了css 中hover 功能
        for (var i=0;i <a.length;i++){
            //写法一:
            a[i].addEventListener('mouseover',function(){
                this.style.backgroundColor='orange';
                this.addEventListener('mouseout',function(){ //此时this 就是div
                this.style.backgroundColor='orangered';
                
            })
            })
           //写法二:
           a[i].addEventListener('mouseover',function(){
                this.style.backgroundColor='orange';
               
            })
            a[i].addEventListener('mouseout',function(){
                this.style.backgroundColor='orangered';
                
            })
        }
    </script>
</body>
</html>

 

posted @ 2021-11-25 12:10  嘉琦  阅读(165)  评论(0)    收藏  举报