zoukankan      html  css  js  c++  java
  • 原生javascript 基础动画函数封装(一)

    <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    <style type="text/css">
    *{ margin:0;padding: 0;}
    div{position: absolute; width: 100px; height: 100px; background: red; left: 0;top: 100px;}
    </style>
    </head>
    <body>
    <button id="btn1">向右</button>
    <button id="btn2">向左</button>
    <div id="box"></div>
    
    <script type="text/javascript">
        window.onload = function(){
            var btn1 = document.getElementById('btn1');
            var btn2 = document.getElementById('btn2');
            var box = document.getElementById('box');
    
            btn1.onclick = function(){
                move(box,12,600);
            }
    
            btn2.onclick = function(){
                move(box,-12,0);
            }
            /*
                obj:要运动的元素
                dir:步长
                target:目标点
            */
            function move(obj,dir,target){
                // 1、清除定时器
                clearInterval(obj.timer);
                // 2、设置定时器
                obj.timer = setInterval(function(){
                    // 3、获取元素当前位置+步长
                    var speed = obj.offsetLeft + dir;
                    console.log(speed)
                    // 4、如果元素当前位置超过目标点,则把当前位置==目标点
                    if( speed > target && dir > 0 || speed < target && dir < 0){
                        speed = target
                    }
                    // 5、设置元素位置
                    obj.style.left = speed + 'px';
                    // 6、判断是否到达目标点,如果到达则停止定时器
                    if(speed == target){
                        clearInterval(obj.timer);
                    }
                },20)
            }
        }
    </script>
    </body>
    </html>
      
  • 相关阅读:
    keep-alive
    关于前端的网络攻击
    Webpack
    https加密
    JS的变量提升
    浏览器
    http请求状态码
    Python程序结构-模块
    Python面向对象编程-继承
    Python语法(高级语法)- 命名空间和作用域
  • 原文地址:https://www.cnblogs.com/javascripter/p/9855928.html
Copyright © 2011-2022 走看看