缓动动画原理

缓动动画原理

正在学习大前端中,有代码和思路不规范不正确的地方往多多包涵,感谢指教


缓动动画就是在网页或者app中某个部分区块移动速度由快到慢 代码如下
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
    
    
            margin: 0;
            padding: 0;
            border: 0;
        }
        button{
    
    
            background-color: pink;
            color: black;
            margin: 20px;
            cursor: pointer;
        }
        div{
    
    
            position: absolute;
            top: 100px;
            width: 100px;
            height: 100px;
            left: 0;
            background-color: red;
            cursor: pointer;
        }
    </style>
</head>
<body>
<button class="btn500">按钮500</button>
<button class="btn800">按钮800</button>
<div></div>
<script>
    var btn500=document.querySelector('.btn500')
    var btn800=document.querySelector('.btn800')
    var div=document.querySelector('div')
    btn500.addEventListener('click',function () {
    
    
        animate(div,500)
    })
    btn800.addEventListener('click',function () {
    
    
        animate(div,800)
    })
    function animate(obj,position) {
    
    
        clearInterval(obj.timeer)
        obj.timeer=setInterval(function () {
    
    
            //步长公式:(目标值-现在的位置)/10
            //步长值写道定时器里面
            //步长取整,不会出现小数的问题
            //var step=Math.ceil((position-obj.offsetLeft)/50)
            var step=(position-obj.offsetLeft)/50
            step=step>0?Math.ceil(step):Math.floor(step)
            if (obj.offsetLeft == position){
    
    
                clearInterval(timeer)//停止计时器
            }
            obj.style.left = obj.offsetLeft + step + 'px'
        },15)
    }
</script>
</body>
</html>

演示效果
在这里插入图片描述

代码解释

这里我们先创建一个函数animate,然后设置两个形参obj,position,分别是对象和位置,这个函数的内容然后先清除定时器,清除的目的是为了不发生连续多次点击从而导致动画速度过块。然后把定时器赋给obj。timeer。这个定时器的的内容就是先定义一个步长step,然后用输入的目标位置-目标距离左侧的位置然后再除以50,因为向右侧移动,距离右侧的距离是越来越远,所以step的值也越来越小,然后判断step是否大于0,这里是判断取大还是取小的。然后判断如果目标距离左侧的位置等于目标位置,那么清除定时器,不移动,如果不等于那么设置目标距离左侧的值不断+步长step的值,从而达到不断移动的效果。然后再看上面,两个按钮按下变调用这个函数,传入两个实参:目标和目的位置,然后调用定时器间隔是15/1000ms




猜你喜欢

转载自blog.csdn.net/weixin_44029226/article/details/113739290