鼠标移入元素弹出消息框,鼠标移出元素,如果进入消息框则不隐藏消息框,不是就隐藏消息框

158 阅读1分钟
<!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>
        .box {
            display: flex;
        }

        .box1 {
            width: 20px;
            height: 20px;
            background: mediumaquamarine;
        }

        .box2 {
            width: 100px;
            height: 100px;
            background: mediumorchid;
            margin-left: 10px;
            display: none;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="box1"></div>
        <div class="box2"></div>
    </div>

    <script>
        const box1 = document.getElementsByClassName("box1")[0]
        const box2 = document.getElementsByClassName("box2")[0]
        let timer = null
        // 监听鼠标移入事件
        box1.onmouseenter = function () {
            timer && clearTimeout(timer)
            // 显示元素
            box2.style.display = "block"
        }
        // 监听鼠标移出事件
        box1.onmouseleave = function () {
            // 500毫秒内 鼠标引入消息框清除定时器
            box2.onmousemove = () => {
                clearTimeout(timer)
            }
            // 鼠标移出消息框隐藏消息框
            box2.onmouseleave = function () {
                box2.style.display = "none"
            }
            // 给500毫秒的缓冲
            const timer = setTimeout(() => {
                box2.style.display = "none"
            }, 500);
        }
    </script>
</body>

</html>