鼠标事件

130 阅读1分钟
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
    .menu{
        width: 50px;
        height: 50px;
        border-radius: 50%;
        background-color: aqua;
        position: absolute;
    }
</style>
</head>

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <a href="http://baidu.com" id="zz">百度</a>
    <div id="demo" style="width: 300px;height: 300px;background: red;">
        <div id="btn" style="width: 100px;height: 100px;background: pink;">demo</div>
    </div>

    <script>
        let demo = document.querySelector('#demo')
        let zz = document.querySelector('#zz')


        demo.onmouseover = function(){
            console.log(111);
        }
        demo.onmouseout = function(){
            console.log(222);
        }
        demo.onmouseenter = function(){
            console.log(111);
        }
        demo.onmouseleave = function(){
            console.log(222);
        }


        // 右击事件
        demo.oncontextmenu = function (e) {
            e.preventDefault();
            let menu = document.querySelector('.menu')
            if (menu) menu.remove()
            menu = document.createElement('div')
            menu.classList.add('menu')
            let menu1 = document.createElement('div')
            menu1.innerHTML = "xxx"
            document.body.appendChild(menu)
            menu.style.left = e.pageX + 'px'
            menu.style.top = e.pageY + 'px'
        }

        window.onclick = e =>{
            let menu = document.querySelector('.menu')
            if (menu && !menu.contains(e.target)) {
                menu.remove()
            }
        }
    </script>
</body>

</html>
</body>

</html>