zoukankan      html  css  js  c++  java
  • 原生js一个简单的拖动

    style如下

    #div1{
      width: 200px;
      height: 20px;
      background: red;
      position: relative;
      margin-top:200px;
      margin-left:auto;
      margin-right:auto;
    }
    #div2{
      width: 20px;
      height: 20px;
      background: blue;
      position: absolute;
      left: 0px;
      top:0px;
    }

    html如下

    <div id="div1">
        <div id="div2"></div>
    </div>
    
    <p id="con"></p>

    js如下

        window.onload = function(){
            div2.onmousedown = function(ev){
                var e = ev || event;
                var disX = e.clientX - this.offsetLeft;
    
                document.onmousemove = function(ev){
                    var e = ev || event;
                    var t = e.clientX - disX;
    
                    if( t <= 0  ) t = 0;
    
                    if( t >= div1.clientWidth - div2.offsetWidth ){
                        t = div1.clientWidth - div2.offsetWidth;
                    };
    
                    var Scale = t / (div1.clientWidth - div2.offsetWidth);
    
                    div2.style.left = t + "px";  
    
                    con.innerHTML = t;
                };
    
                document.onmouseup = function (){
                    document.onmousemove = null;
                    document.onmouseup = null;  
                };
            }
        }
  • 相关阅读:
    python基础(5)
    python基础(4)
    python基础(3)
    python基础(2)
    第一个python程序(2)
    第一个python教程(1)
    【jQuery】
    【JavaScript】
    【练习】HTML+CSS
    【练习】Html
  • 原文地址:https://www.cnblogs.com/zard23/p/9144745.html
Copyright © 2011-2022 走看看