js实现鼠标移入移出元素出来缩进的动画

52 篇文章 1 订阅
38 篇文章 0 订阅
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>测试</title>
    <style>
        body,
        div,
        span {
            margin: 0;
            padding: 0;
        }
        
        #hide {
            width: 200px;
            height: 200px;
            background-color: aqua;
            position: relative;
            left: -200px;
        }
        
        .out {
            display: inline-block;
            width: 15px;
            background-color: blueviolet;
            position: absolute;
            right: -15px;
            top: 50%;
            transform: translateY(-50%);
        }
    </style>
</head>

<body>
    <div id="hide"><span class="out">出来</span></div>
    <script>
        window.onload = function() {
            var hide = document.getElementById("hide");
            hide.onmouseover = function() {
                startMove(0, 10);
            };
            hide.onmouseout = function() {
                startMove(-200, -10);
            };
        };

        var timer = null;

        // function startMoveout() {
        //     // 防止连续移入元素会生成多个计时器,所以进入之前先清除
        //     clearInterval(timer);
        //     var hide = document.getElementById("hide");
        //     timer = setInterval(function() {
        //         if (hide.offsetLeft == 0) {
        //             clearInterval(timer);
        //         } else {
        //             hide.style.left = hide.offsetLeft + 1 + 'px';
        //         }
        //     }, 17);
        // }

        // function startMovein() {
        //     // 防止连续移入元素会生成多个计时器,所以进入之前先清除
        //     clearInterval(timer);
        //     var hide = document.getElementById("hide");
        //     timer = setInterval(function() {
        //         if (hide.offsetLeft == -200) {
        //             clearInterval(timer);
        //         } else {
        //             hide.style.left = hide.offsetLeft - 1 + 'px';
        //         }
        //     }, 17);
        // }

        // 将上面的代码合并
        function startMove(target, speed) {
            // 防止连续移入元素会生成多个计时器,所以进入之前先清除
            clearInterval(timer);
            var hide = document.getElementById("hide");
            timer = setInterval(function() {
                if (hide.offsetLeft == target) {
                    clearInterval(timer);
                } else {
                    hide.style.left = hide.offsetLeft + speed + 'px';
                }
            }, 17);
        }
    </script>
</body>

</html>

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值