event 和 this 的区别

event 和 this 的区别

事件对象 event

​ 定义:包含事件相关信息的对象;这个事件例有事件触发时的相关信息

​ 用于记录:哪个标签触发了该事件、哟用户按下哪个键触发该事件、鼠标位置

event.target 指的是所记录的事件对象

环境对象 this

​ 定义:环境对象指的是函数内部特殊的变量this,它代表当前函数运行时所处的环境

​ 谁调用函数、监听事件;是就是this;箭头函数内this指向上一级,箭头函数本身无this

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        li {
            list-style-type: none;
        }
        
        a {
            text-decoration: none;
            font-size: 14px;
        }
        
        .nav {
            margin: 100px;
        }
        
        .nav>li {
            position: relative;
            float: left;
            width: 80px;
            height: 41px;
            text-align: center;
        }
        
        .nav li a {
            display: block;
            width: 100%;
            height: 100%;
            line-height: 41px;
            color: #333;
        }
        
        .nav>li>a:hover {
            background-color: #eee;
        }
        
        .nav ul {
            display: none;
            position: absolute;
            top: 41px;
            left: 0;
            width: 100%;
            border-left: 1px solid #FECC5B;
            border-right: 1px solid #FECC5B;
        }
        
        .nav ul li {
            border-bottom: 1px solid #FECC5B;
        }
        
        .nav ul li a:hover {
            background-color: #FFF5DA;
        }
    </style>
    <script src="jquery.min.js"></script>
</head>

<body>
    <ul class="nav">
        <li>
            <a href="#">微博</a>
            <ul>
                <li>
                    <a href="">私信</a>
                </li>
                <li>
                    <a href="">评论</a>
                </li>
                <li>
                    <a href="">@我</a>
                </li>
            </ul>
        </li>
    </ul>
    <script>
        const lis = document.querySelectorAll(".nav > li")
        for(let i = 0;i < lis.length;i++){
            lis[i].addEventListener("mousemove",function (e) {
                this.querySelector("ul").style.display = "block"
                console.log(e.target)  //指 a 标签对象
                console.log(this)	  //指 li 标签对象
            })
            lis[i].addEventListener("mouseout",function () {
                this.querySelector("ul").style.display = "none"
            })
        }
    </script>
</body>

</html>
posted @ 2023-05-14 19:10  Agiser0  阅读(16)  评论(0编辑  收藏  举报