JS---- mouseenter和mouseover的区别以及动画函数的封装

mouseenter 和mouseover的区别

  • 当鼠标移动到元素上时就会触发mouseenter 事件
  • 类似 mouseover,它们两者之间的差别是
  • mouseover 鼠标经过自身盒子会触发,经过子盒子还会触发。mouseenter 只会经过自身盒子触发
  • 之所以这样,就是因为mouseenter不会冒泡
  • 跟mouseenter搭配鼠标离开 mouseleave 同样不会冒泡
  • Mouseover mouseoutmouseenter mouseleave

代码示例:

mouseover:

father.addEventListener('mouseover', function(e) {
            console.log('鼠标移入了父盒子');
        })
        son.addEventListener('mouseover', function(e) {
            console.log('鼠标移入了子盒子');
        })

在这里插入图片描述

在这里插入图片描述

鼠标移入子盒子还是会触发移入父盒子的函数

mouseenter:

father.addEventListener('mouseenter', function(e) {
            console.log('鼠标移入了父盒子');
        })
        son.addEventListener('mouseenter', function(e) {
            console.log('鼠标移入了子盒子');
        })

在这里插入图片描述

在这里插入图片描述
没有事件冒泡


动画函数封装

动画实现原理:

通过定时器 setInterval() 不断移动盒子位置。

  • 获得盒子当前位置

  • 让盒子在当前位置加上1个移动距离

  • 利用定时器不断重复这个操作

  • 加一个结束定时器的条件

  • 注意此元素需要添加定位,才能使用element.style.left

代码示例:

<!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>
        .father {
            position: absolute;
            width: 300px;
            height: 300px;
            background-color: blueviolet;
        }
        
        .son {
            width: 150px;
            height: 150px;
            background-color: brown;
        }
    </style>
</head>

<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <script>
        let father = document.querySelector('.father');

        function animate(obj, target) {
            // 封装一个动画函数  参数1 为元素对象 (操作哪个元素)  参数2 为停止动画的条件


            // 避免定时器的bug  使用之前先清除
            clearInterval(obj.timer);
            // 设置定时器
            obj.timer = setInterval(function() {
                // 如果满足了停止动画的条件就清除定时器  本质就是停止定时器
                if (obj.offsetLeft >= target) {
                    clearInterval(obj.timer);
                }
                // 没30毫秒  元素的left加1像素
                obj.style.left = obj.offsetLeft + 1 + 'px';
            }, 30)
        }
        // 执行函数 传入元素和停止动画的条件
        animate(father, 500);
    </script>
</body>

</html>
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值