jQuery之鼠标事件:mouseover()和mouseout()、mouseenter()和mouseleave()、hover()

526 阅读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>
        /*给盒子设置宽高和背景颜色*、
        div{width: 200px;height: 200px;background-color: blueviolet;}
    </style>
</head>

<body>
    <div>
        /* 给div盒子里面的p标签设置宽高 */
        <p style="width: 80px;height: 80px;background-color: burlywood;"></p>
    </div>
    <script src="./jquery-1.12.4.js"></script>
    <script>
        /* 鼠标指针移过时 */
        /* 进入div触发,控制台打印下面这句话,不出去不触发 */
        $('div').mouseover(function(){
             console.log('mouseover鼠标指针移过时');
        })
        
        /* 鼠标指针移出时,控制台打印下面这句话 */
        $('div').mouseout(function(){
             console.log('mouseout鼠标指针移出时');
        })

        /* 鼠标指针进入时 */
        $('div').mouseenter(function(){
             console.log('mouseenter鼠标指针进入时');
        })
        
        /* 鼠标指针离开时 */
        $('div').mouseleave(function(){
             console.log('mouseleave鼠标指针离开时');
        })

        /* 区别 */
        // mouseover 进入子元素(例子中的p元素)的时候也触发
        // mouseout 移出子元素(例子中的p元素)的时候也触发
        
        // mouseenter 进入子元素的时候不触发
        // mouseleave 移出子元素的时候不触发

        /* hover是由mouseenter和mouseleave组成的  */
        //hover(a,b)有两个参数
        $('div').hover(function(){
            console.log('鼠标移入')
        },function(){
            console.log('鼠标移出')
        })
    </script>
</body>
</html>