zoukankan      html  css  js  c++  java
  • 小方块向左向右运动

    代码

    <!DOCTYPE html>
    <html lang="en">
    
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
    
            #box {
                width: 100px;
                height: 100px;
                background: darkmagenta;
                position: absolute;
                left: 0;
                top: 30px;
            }
        </style>
    </head>
    
    <body>
        <button id='right'>向右走</button>
        <button id='left'>向左走</button>
        <div id="box"></div>
    
        <script>
            var right = document.getElementById('right');
            var left = document.getElementById('left');
            var box = document.getElementById('box');
            var timer = null;
            // 向右走
            right.onclick = function () {
                run(box,'left',5,500)
            }
    
            // 向左走
            left.onclick = function () {
                run(box,'left',10,0)
            }
    
            function run(ele,attr,step,target) {
                step = target>parseInt(getStyle(ele, attr))? step :-step;
                // if( target>parseInt(getStyle(ele, attr))){
                //     step = step;
                // }else{
                //     step = -step;
                // }
                clearInterval(timer);
                timer = setInterval(function () {
                    var dis = parseInt(getStyle(ele, attr)) + step;
                    if (dis <= target && step < 0 || dis >= target && step > 0) {
                        dis = target;
                        clearInterval(timer);
                    }
                    ele.style[attr] = dis + 'px';
                }, 50)
            }
    
    
    
    
            // 获取元素样式
            function getStyle(ele, attr) {
                if (window.getComputedStyle) {
                    return getComputedStyle(ele)[attr];
                } else {
                    return ele.currentStyle[attr];
                }
            }
        </script>
    </body>
    
    </html>

    效果

  • 相关阅读:
    host 文件位置
    Django 前后端分离开发配置 跨域
    pycharm 关闭单词拼写检查(Typo: In word 'cacheable' )
    Python : argument name should be lowercase 警告处理解决方法
    pycharm 变量名 (Shadows built-in name 'id' )问题
    三体
    12.URL下载网络资源
    11.UDP多线程在线咨询
    10.UDP实现聊天
    9.UDP
  • 原文地址:https://www.cnblogs.com/shihaiying/p/13229997.html
Copyright © 2011-2022 走看看