Js缓冲运动

3 篇文章 0 订阅

Js缓冲运动代码

<!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>
     <!--为html添加样式-->
    <style>
        .wrapper{
            width: 400px;
            height: 80px;
            cursor: pointer;
            background: rgb(0, 204, 255);
            position: absolute;
            left: -400px;
            top: 20px;
        }
        .wrapper span{
            width: 50px;
            height: 80px;
            background: #008c8c;
            position: absolute;
            right: -50px;
            top: 0px;
        }
    </style>
</head>
<body>
	<!--div元素-->
    <div class="wrapper">
        <span></span>
    </div>
    
    <script>
        var timer = null;
        var oDiv = document.getElementsByClassName('wrapper')[0];
        //鼠标悬浮事件
        oDiv.onmouseover = function(){
            console.log("over");
            startMove(this,0);
        }
        //鼠标移开事件
        oDiv.onmouseleave = function(){
            console.log("leave");
            startMove(this,-400)
        }
        // 封装函数获取元素的属性值
        // dom 元素
        // attr 属性名
        function getStyle(dom,attr){
            if(window.getComputedStyle){
                return window.getComputedStyle(dom,null)[attr];
            }else{
                return dom.currentStyle[attr];
            }
        }
        // 物体的速度 距离木笔哦啊点越近就越小,当到达目标点时,速度减小为0
        function startMove(dom,target){
            clearInterval(timer);
			timer = setInterval(function(){
                // (300 - left)/7 
                iSpeed = (target - oDiv.offsetLeft)/7;
                //通过三目判断iSpeed是否>0 让div能贴合
                iSpeed = iSpeed>0?Math.ceil(iSpeed):Math.floor(iSpeed);
                if(oDiv.offsetLeft == target){
                    clearInterval(timer);
                }
                //设置style.left 属性值
                oDiv.style.left = oDiv.offsetLeft + iSpeed + 'px';
            },30);
        }
    </script>
</body>
</html>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

师兄白泽

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值