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;  
                };
            }
        }
  • 相关阅读:
    选择结构
    算法和流程图
    存储信息和信息运算
    计算机组成原理
    计算机硬件组装
    认识计算机硬件
    认识操作系统
    DOS简介
    计算机软件知识
    易企cms截取字段方法
  • 原文地址:https://www.cnblogs.com/zard23/p/9144745.html
Copyright © 2011-2022 走看看