首页 > 代码库 > js原生拖拽

js原生拖拽

style样式

<style type="text/css">
        #box{
            width: 100px;
            height: 100px;
            background: deeppink;
            position: absolute;
            border: 2px pink solid;
        }
        #boxT{
            width: 80px;
            height: 80px;
            background: pink;
            position: absolute;
            border: 10px deeppink solid;
        }
        #boxS{
            width: 60px;
            height: 60px;
            background: yellow;
            position: absolute;
            border: 10px deeppink solid;
        }
    </style>

body布局

  <div id="box">
        <div id="boxT">
            <div id="boxS"></div>
        </div>
    </div>

js代码

<script type="text/javascript">

    var box=document.getElementById(box);

    box.onmousedown = function (ev){
        var ev=ev||window.event;
        var oldX=ev.clientX-box.offsetLeft;
        var oldY=ev.clientY-box.offsetTop;
        document.onmousemove = function (ev){
        var ev=ev||window.event;
        var factX=ev.clientX-oldX;
        var factY=ev.clientY-oldY;
        box.style.left=factX+px;
        box.style.top=factY+px;
        }
        document.onmouseup = function (){
            document.onmousemove = null;
        }
    }
    </script>

 

js原生拖拽