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>

 

posted @ 2017-06-24 08:40  谁是李慧  阅读(208)  评论(0编辑  收藏  举报