码迷,mamicode.com
首页 > Web开发 > 详细

js实现可拖拽的div

时间:2017-03-18 01:16:11      阅读:402      评论:0      收藏:0      [点我收藏+]

标签:第一个   tor   put   char   lin   ble   get   dev   eee   

实现一个div可以被拖拽,代码如下所示:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>zzw_drap</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        #box {
            position: absolute;
            top: 100px;
            left: 200px;
            width: 500px;
        }
        #bar {
            padding-left:50px; 
            height: 50px;
            line-height: 50px;
            color: white;
            background-color: #aaa;
            cursor: move;
        }
        #content {
            padding:30px 0 0 50px ;
            height: 300px;
            background-color: #eee;
        }
    </style>
</head>
<body>
    <div id="box">
        <div id="bar">可拖拽头部</div>
        <div id="content">这里是内容</div>
    </div>

    <script>


    /*
    * zzw.drag 2017-3
    * js实现div可拖拽
    * @params bar 可以点击拖动的元素
    * @params box 拖动的整体元素 必须是position: absolute;
    * 思想:鼠标的clienX/clientY相对值设置为父元素的left/top的相对值
    */

    var dragBox = function (drag, wrap) {

       function getCss(ele, prop) {
            return parseInt(window.getComputedStyle(ele)[prop]);
       }

       var initX,
           initY,
           dragable = false,
           wrapLeft = getCss(wrap, "left"),
           wrapRight = getCss(wrap, "top");

       drag.addEventListener("mousedown", function (e) {
            dragable = true;
            initX = e.clientX;
            initY = e.clientY;
       }, false); 

       drag.addEventListener("mousemove", function (e) {
            if (dragable === true ) {
                var nowX = e.clientX,
                    nowY = e.clientY,
                    disX = nowX - initX,
                    disY = nowY - initY;
                wrap.style.left = wrapLeft + disX + "px";
                wrap.style.top = wrapRight + disY + "px";
            }
       });

       drag.addEventListener("mouseup", function (e) {
            dragable = false;
            wrapLeft = getCss(wrap, "left");
            wrapRight = getCss(wrap, "top");
       }, false); 

    };

    dragBox(document.querySelector("#bar"), document.querySelector("#box"));
    </script>
</body>
</html>

其中我们可以直接使用封装好的函数,它接受两个参数,第一个是可以点击拖拽的元素,第二个是父元素。  注意:父元素的postion设置为 absolute才可以使用。

 

js实现可拖拽的div

标签:第一个   tor   put   char   lin   ble   get   dev   eee   

原文地址:http://www.cnblogs.com/zhuzhenwei918/p/6569295.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!