js||运动框架

本文探讨JavaScript中的运动框架,包括匀速运动、缓冲运动、多物体运动和完美运动框架的实现与优化。针对侧边栏淡入淡出、缓冲效果、多物体淡入淡出及透明度运动等问题,提出了解决方案,并分析了运动框架在处理小数和取整时的潜在bug。
摘要由CSDN通过智能技术生成

运动框架

匀速运动

<!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>animate</title>
</head>
<style>
    .div1 {
        position: absolute;
        top: 50px;
        left: 0;
        width: 200px;
        height: 200px;
        background-color: pink;
    }
</style>
<body>
    <input type="button" value="start" class="but1">
    <div class="div1"></div>
    <input type="button" value="stop" class="but2"></div>
</body>
<script>
    var button = document.querySelector('.but1')
    button.addEventListener("click", startMove) //汗,没想到连这个也没练熟,1、事件是click不是onclick 2、函数是一个函数名就行,不用加上括号
    var butt2 = document.querySelector('.but2')
    butt2.onclick = stop //这个stop不加括号,是个函数名就行

    var timer = null

    function stop () {
        clearInterval(timer)
    }

    //每次点击按钮都会开一个定时器,所以速度不是每次加上30ms了,是加 30*n次了
    //解决方法:只开一个定时器就行了
    function startMove () {
        var speed = 7
        var div = document.querySelector(".div1")
        //每次开定时器之前先把前面的给关掉
        clearInterval(timer)
        //再次开一个新的定时器
        timer = setInterval(function() {
            div.style.left = div.offsetLeft + speed + 'px' //这个数字就是运动的速度
            console.log(div.offsetLeft)
        }, 30)
    }
</script>
</html>

匀速运动的停止条件

if(target - offsetxx <= speed) { //为什么要小于speed,因为speed实际上是一次移动的步数,一次移动不步数不够了就直接停止,这时候因为有误差所以直接等于target
    clear 
    element.style.xx = target 
}

例子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>侧边栏</title>
</head>
<style>
    .div1 { 
        position: absolute;
        left: -150px;
        width: 150px;
        height: 200px;
        background-color: pink;
    }
    .div1 span {
        position:absolute;
        right: -20px;
        top: 70px;
        width: 20px;
        height: 60px;
        line-height: 20px;
        background-color: skyblue;
    }
</style>
<body>
    <div class="div1">
        <span>分享到</span>
    </div>
</body>
<script>
    var div = document.querySelector(".div1")
    var timer = null

    div.onmouseover = start

    function start() {
        clearInterval(timer)

        timer = setInterval(function() {
            if(div.offsetLeft == 0) {
                clearInterval(timer)
            } else {
                div.style.left = div.offsetLeft + 10 + 'px'
                console.log(div.style.left)
            }
        }, 30)
    }
</script>
</html>
优化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>侧边栏</title>
</head>
<style>
    .div1 { 
        position: absolute;
        left: -150px;
        width: 150px;
        height: 200px;
        background-color: pink;
    }
    .div1 span {
        position:absolute;
        right: -20px;
        top: 70px;
        width: 20px;
        height: 60px;
        line-height: 20px;
        background-color: skyblue;
    }
</style>
<body>
    <div class="div1">
        <span>分享到</span>
    </div>
</body>
<script>
    var div = document.querySelector(".div1")
    var timer = null

    div.onmouseover = start
    div.onmouseout = out

    function out() {
        clearInterval(timer)

        timer = setInterval(function() {
            if(div.offsetLeft == -150) {
                clearInterval(timer)
            } else {
                div.style.left = div.offsetLeft - 10 + 'px'
            }
        }, 30)
    }

    function start() {
        clearInterval(timer)

        timer = setInterval(function() {
            if(div.offsetLeft == 0) {
                clearInterval(timer)
            } else {
                div.style.left = div.offsetLeft + 10 + 'px'
            }
        }, 30)
    }
</script>
</html>
优化2 合并重复的代码
<!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>侧边栏</title>
</head>
<style>
    .div1 { 
        position: absolute;
        left: -150px;
        width: 150px;
        height: 200px;
        background-color: pink;
    }
    .div1 span {
        position:absolute;
        right: -20px;
        top: 70px;
        width: 20px;
        height: 60px;
        line-height: 20px;
        background-color: skyblue;
    }
</style>
<body>
    <div class="div1">
        <span>分享到</span>
    </div>
</body>
<script>
    var div = document.querySelector(".div1")
    var timer = null

    div.onmouseover = function() {
        start(0)
    }
    div.onmouseout = function() {
        start(-150)
    }


    //合并代码的方式: 把n段代码中不同的地方挑出来当函数的参数传进去
    //tips:功能一样的情况下,参数越少越好
    function start(target) {
        clearInterval(timer)

        timer = setInterval(function() {

            var speed = 0

            if(div.offsetLeft > target) {
                speed = -10
            } else {
                speed = 10
            }

            if(div.offsetLeft == target) {
                clearInterval(timer)
            } else {
                div.style.left = div.offsetLeft + speed + 'px'
                console.log(div.style.left)
            }
        }, 30)
    }
</script>
</html>

例子2: 淡入淡出

<!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>透明度</title>
</head>
<style>
    .div1 {
        width: 200px;
        height: 200px;
        background-color: skyblue;
        opacity: 0.3;
    }
</style>
<body>
    <div class="div1"></div>
</body>
<script>
    var div = document.querySelector(".div1")
    var timer = null

    div.onmouseover = function() {
        startMove(1)
    }
    div.onmouseout = function() {
        startMove(0.3)
    }

    function startMove(target) {
        clearInterval(timer) 
        var speed = 0
        if(getComputedStyle(div,null)['opacity'] < target) {
                speed = 0.1
            } else {
                speed = -0.1
            }
        timer = setInterval (function() {
            if(getComputedStyle(div,null)['opacity'] == target) {
                clearInterval(timer)
            } else {
                var opa = getComputedStyle(div,null)['opacity'] //getComputedStyle(div,null)['opacity']的返回值是string,需要转换成float
                div.style.opacity = parseFloat(opa)+ speed
                console.log(parseFloat(opa))
            }
            
        }, 30)
    }
</script>
</html>

缓冲运动

  • 当距离终点的距离越来越大的时候,速度也越来越大
  • 当距离终点的距离越来越小的时候,速度也越来越慢
  • 速度和距离成正比
<!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>缓冲运动框架</title>
</head>
<style>
    .div1 {
        position: absolute;
        width: 100px;
        height: 100px;
        background-color: green;
        left: 0;
        top: 50px;
    }
</style>
<body>
    <div class="div1"></div>
    <input type="button" value="start">
</body>
<script>
    var but = document.querySelector("input")
    but.onclick = startMove

    function startMove() {
        var div = document.querySelector(".div1")

        setInterval(() => {
            //由于除法的知识,分母越大,速度就越小,速度就越慢
            //300是终点的位置
            var speed = (300 - div.offsetLeft) / 20 
            div.style.left = div.offsetLeft + speed + "px"
        }, 30);
    }
</script>
</html>

优化

  • 问题一:

    现在这里的问题是,我们在300px的时候有个div作为标准, 我们看到,到了300的时候,这个绿色的div没有全部在300的右面

console一下,发现是287

console一下速度

这是为什么

px是计算机接受的最小的距离单位,如果写的是29.5px会变成29px不会四舍五入,计算进看到小数,直接把小数点后面去掉了

speed处理下

            speed = Math.ceil(speed)
  • 问题2:

 speed = Math.floor(speed)

综合起来是这样:

speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)

但凡用到缓冲运动,一定要取整!!!

潜在问题: 目标值不是整数的时候,

//最终版本
<!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>缓冲运动框架</title>
</head>
<style>
    .div1 {
        position: absolute;
        width: 100px;
        height: 100px;
        background-color: green;
        left: 600px;
        top: 50px;
    }
    .div2 {
        position: absolute;
        top: 0;
        left: 300px;
        width: 1px;
        height: 300px;
        background-color: black;
    }
</style>
<body>
    <div class="div1"></div>
    <div class="div2"></div>
    <input type="button" value="start">
</body>
<script>
    var speed = 0
    var but = document.querySelector("input")
    but.onclick = startMove
    var div = document.querySelector(".div1")
    function startMove() {

        setInterval(() => {
            speed = (300 - div.offsetLeft) / 10 //由于除法的知识,分母越大,速度就越小,速度就越慢
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
            div.style.left = div.offsetLeft + speed + "px"
        }, 30);
    }
</script>
</html>

多物体运动

框架

<!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>多物体</title>
</head>
<style>
    div {
        height: 50px;
        width: 100px;
        background-color: green;
        margin: 10px;
    }
</style>
<body>
    <div></div>
    <div></div>
    <div></div>
</body>
<script>
    //var timer = null
    var div = document.querySelectorAll("div")

    for (var i = 0; i < div.length; i++) {
        div[i].timer = null
        div[i].onmouseover = function() {
            start(this, 400)
        }
        div[i].onmouseout = function() {
            start(this, 100)
        }
    }

    function start (obj, target) {
        clearInterval(obj.timer) 
        //多个物体同时移动的话,只有一个定时器,可能第一个物体还没动完, 第二个就开始动了,会把前面的定时器先清除,这样第一个就会定住不动,或者做出一些鬼畜的行为。

        //解决方法
        // 1. 开n个定时器
        obj.timer = setInterval(() => {
            var speed = (target - obj.offsetWidth) / 6
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)

            if(obj.offsetWidth == target) {
                clearInterval(obj.timer)
            } else {
                obj.style.width = obj.offsetWidth + speed + 'px'
                console.log(obj.style.width)
            }

        }, 30);
    }
</script>
</html>

多物体的淡入淡出

<!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>多个物体淡入淡出</title>
</head>
<style>
    div {
        float: left;
        width: 100px;
        height: 100px;
        margin: 20px;
        background-color: skyblue;
        opacity: 0.3;
    }
</style>
<body>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</body>
<script>
var div = document.querySelectorAll("div")

for (var i = 0; i < div.length; i++) {
    div[i].timer = null
    //多物体最好什么东西都不要共用
    //缓动有小数点太麻烦了,还是用一个透明度的变量把
    div[i].opa = 30
    
    div[i].onmouseover = function() {
        start(this, 100)
    }
    div[i].onmouseout = function() {
        start(this, 30)
    }
}

    function start (obj, target) {
        clearInterval(obj.timer) 

        obj.timer = setInterval(() => {
            var speed = (target - obj.opa) / 6
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed )

            if(obj.opa == target) {
                clearInterval(obj.timer)
            } else {
                obj.opa += speed
                obj.style.opacity = obj.opa / 100
                console.log(obj.style.opacity)
            }
        }, 30);
    }
</script>

</html>

任意值的运动框架

offset的bug

所以之前用了offset的都有潜在的bug

<!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>offset的bug</title>
</head>
<style>
    div {
        width: 200px;
        height: 200px;
        border: 1px solid;
        background-color: skyblue;
    }
</style>
<body>
    <div></div>
</body>
<script>
    //offsetWidth 得到的是box的所有的东西,padding border之类的。
    //解决方法:不要offset了
    var div = document.querySelector("div")

    function getStyle(obj, name) {
        return getComputedStyle(obj, null)[name]
    }

    setInterval(() => {
        div.style.width = parseInt(getStyle(div, "width")) -1 + 'px'
    }, 30);
</script>
</html>
初步
  • 问题1: 如果更改透明度 opacity是个小数, parseInt直接解析错误
  • 问题2:opacity的单位也没有px这样直接错误了
<!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>任意值的运动框架</title>
</head>
<style>
    div {
        float: left;
        width: 200px;
        height: 200px;
        margin: 20px;
        background-color: skyblue;
    }
</style>
<body>
<div class="one"></div>
<div class="two"></div>
</body>
<script>
    var one = document.querySelector(".one")
    one.onmouseover = function() {
        start(this, 'height', 400)
    }
    one.onmouseout = function() {
        start(this, 'height', 200)
    }

    var two = document.querySelector(".two")
    two.onmouseover = function() {
        start(this, 'width', 400)
    }
    two.onmouseout = function() {
        start(this, 'width', 200)
    }

    function getStyle(obj, attr) {
        return getComputedStyle(obj, null)[attr]
    }

    function start(obj, attr, target) {
        clearInterval(obj.timer)
        obj.timer = setInterval(() => {
            var current = parseInt(getStyle(obj, attr))
            var speed = (target - current) / 6
            speed > 0 ? Math.ceil(speed) : Math.floor(speed)

            if(current == target) {
                clearInterval(obj.timer)
            } else {
                obj.style[attr] = current + speed + 'px'
            }
        }, 30);
    }
</script>

</html>
改良: 带透明度的运动框架
<!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>任意值的运动框架</title>
</head>
<style>
    div {
        float: left;
        width: 200px;
        height: 200px;
        margin: 20px;
        background-color: skyblue;
        opacity: 0.3;
    }
</style>
<body>
<div class="one"></div>
<div class="two"></div>
</body>
<script>
    var one = document.querySelector(".one")
    one.onmouseover = function() {
        start(this, 'opacity', 100)
    }
    one.onmouseout = function() {
        start(this, 'opacity', 30)
    }

    var two = document.querySelector(".two")
    two.onmouseover = function() {
        start(this, 'width', 400)
    }
    two.onmouseout = function() {
        start(this, 'width', 200)
    }

    function getStyle(obj, attr) {
        return getComputedStyle(obj, null)[attr]
    }

    function start(obj, attr, target) {
        clearInterval(obj.timer)
        obj.timer = setInterval(() => {
            var current = 0
            //判断一下传进来的值是否为opacity
            if(attr === 'opacity') {
                current = parseFloat(getStyle(obj, attr)) * 100
            } else {
                current = parseInt(getStyle(obj, attr))
            }
            var speed = (target - current) / 6
            speed > 0 ? Math.ceil(speed) : Math.floor(speed)

            if(current == target) {
                clearInterval(obj.timer)
            } else {
                if(attr === 'opacity') {
                    obj.style.opacity = (current + speed) / 100
                } else {
                    obj.style[attr] = current + speed + 'px'
                }
            }
        }, 30);
    }
</script>

</html>

链式运动

回调函数

运动停止时, 执行函数

运动停止时,开始下一次运动

function getStyle(obj, attr) {
    return getComputedStyle(obj, null)[attr]
}

//这里多了一个参数 ,类型是函数,在运动结束的时候被调用
function start(obj, attr, target, fnEnd) {
    clearInterval(obj.timer)
    obj.timer = setInterval(() => {
        var current = 0
        //判断一下传进来的值是否为opacity
        if(attr === 'opacity') {
            target = target * 100
            //current = parseFloat(getStyle(obj, attr)) * 100 //会出现问题,数值不精准
            current = Math.round(parseFloat(getStyle(obj, attr)) * 100)
            //console.log(current)
        } else {
            current = parseInt(getStyle(obj, attr))
        }
        var speed = (target - current) / 6
        speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)

        //console.log(Math.round(speed))

        if(current == target) {
            clearInterval(obj.timer)
            if(fnEnd) {
                fnEnd()
            }
        } else {
            if(attr === 'opacity') {
                obj.style.opacity = (current + Math.round(speed)) / 100 
                //console.log(obj.style.opacity)
            } else {
                obj.style[attr] = current + speed + 'px' 
            }
        }
    }, 30);
}
<!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>链式运动框架</title>
</head>
<style>
    .div1 {
        width: 100px;
        height: 100px;
        background-color: skyblue;
        opacity: 0.3;
    }
</style>
<body>
    <div class="div1"></div>
</body>
<script src="../Slideshow/move.js"></script>
<script>
    //其实就多了一个参数,回调函数
    var div = document.querySelector(".div1")

    div.onmouseover = function () {
        start(div, "width", 300, function() {
            start(div, 'height', 300, function() {
                start(div, 'opacity', 1) 
            })
        })
    }
</script>
</html>

完美运动框架

  • 链式运动框架的问题: 一个对象的多个属性同时变就不行了
function getStyle(obj, attr) {
    return getComputedStyle(obj, null)[attr]
}

//这里多了一个参数 ,类型是函数,在运动结束的时候被调用
function start(obj, json, fnEnd) {
    clearInterval(obj.timer)

    obj.timer = setInterval(() => {
        var isStop = true //假设所有的值都到了
        for(var attr in json) {
            var current = 0
            //判断一下传进来的值是否为opacity
            if(attr === 'opacity') {
                if(json[attr] <= 1) {
                    json[attr] = parseInt(json[attr] * 100) //没有判断这里会越来越大,死循环
                } 
                //console.log(json[attr])
                
                //current = parseFloat(getStyle(obj, attr)) * 100 //会出现问题,数值不精准
                current = Math.round(parseFloat(getStyle(obj, attr)) * 100)
                //console.log(current)
            } else {
                current = parseInt(getStyle(obj, attr))
            }
            var speed = (json[attr] - current) / 6
            speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed)
            console.log('current is ' + current + ',' + 'target is ' + json[attr])
            if (current !== json[attr]) {
                isStop = false
            }
            //console.log(Math.round(speed))
            //等到所有东西都到了--关闭
            //如果没有不到的--关闭

            
            if(attr === 'opacity') {
                obj.style.opacity = (current + Math.round(speed)) / 100 
                //console.log(obj.style.opacity)
            } else {
                obj.style[attr] = current + speed + 'px' 
            }
            
        }
        if(isStop) {
            clearInterval(obj.timer)
            //alert('aaa')
            if(fnEnd) {
                fnEnd()
            }
        }
        //console.log(isStop)
    }, 30);
}
演变
函数模式
start(target)匀速/缓动
start(obj, target)多物体
start(obj, attr, target)任意值
start(obj, attr, target, fn)链式运动
start(obj, json, fn)完美
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值