Js之鼠标事件-鼠标事件

一 、常用到的鼠标事件

类型 事件
click 单机鼠标左键时发生,如果右键也按下则不会发生
dbclick 双击鼠标左键时发生,如果右键也按下则不会发生
mousedown 单击任意一个鼠标按钮时发生
mouseover 鼠标指针位于某个元素上且将要移除元素的边界时发生
mouseout 鼠标指针移出某个元素到另一个元素上时发生
mouseup 松开任意一个鼠标按钮时发生
mousemove 鼠标在某个元素上时持续发生

二、鼠标点击事件

鼠标点击事件包括 click(点击),dbclick(双击),mousedown(按下)和 mouseup(松开)四个。其中 click 事件比较常用,而mousedown 和 mouseup事件类型多用于鼠标施放,拉伸操作中。当这些事件处理函数的返回值为false时,会禁止绑定对象的默认行为。

实例如下:

<!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>
        *{
            margin: 0;
            padding: 0;
        }
        div {
            width: 200px;
            height: 200px;
            background-color: skyblue;
        }
    </style>
</head>
<body>
    <div></div>
    <script>
        var div = document.querySelector('div')
        // 鼠标点击盒子变粉
        div.addEventListener('click',function(){
            this.style.background = 'pink'
        })

    </script>
</body>
</html>

三、鼠标经过事件

鼠标经过包括移入和移出两种事件类型。当移动鼠标指针到某个元素上时,将触发 mouseover事件。而当把鼠标指针移出某个元素时,将触发mouseout事件。如果从父元素中移动到子元素中,也会触发元素的mouseover事件类型。

实例如下:

<!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>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            width: 200px;
            height: 200px;
            background-color: skyblue;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        var div = document.querySelector('div')
        // 鼠标移入盒子变粉
        div.addEventListener('mouseover', function () {
            this.style.background = 'pink'
        })
        // 鼠标移出盒子变黑
        div.addEventListener('mouseout', function () {
            this.style.background = 'black'
        })
    </script>
</body>

</html>

四、鼠标移动事件

mousemove 事件类型是一个实时响应的事件,当鼠标指针的位置发生变化时(至少移动一个像素),就会触发mousemove事件。该事件响应的灵敏度主要参考鼠标指针的移动速度块慢以及浏览器跟踪更新的速度。

实例如下:

<!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>
        * {
            margin: 0;
            padding: 0;
        }

        div {
            width: 200px;
            height: 200px;
            background-color: skyblue;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        var div = document.querySelector('div')
        // // 鼠标在盒子内移动后盒子变粉
        div.addEventListener('mousemove', function () {
            this.style.background = 'pink'
        })
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/cx1361855155/article/details/126157474