拖动

2017-01-04  本文已影响15人  duJing

拖动是一件非常酷的事情。你点击某个对象,并按住鼠标不放,将鼠标移动到另一个区域,然后释放鼠标按钮将对象放在这里。
下面是一个简单的案例:
HTML部分:注意,拖动元素一定要为绝对定义,即position = absolute;

<div style="position:absolute;height:100px;width:100px;background:red" class="draggable"></div>
<script src="dome.js"></script>

JS部分(dome.js):

var EventUtil = {
    // 获取事件和目标
    getEvent : function (event) {
        return event ? event : window.event;
    },
    getTarget : function (event) {
        return  event.target || event.srcElement;
    },
    // 添加监听事件
    addEvent : function (element, type, handler) {
        if (element.addEventListener)
        {
            element.addEventListener(type, handler, false);
        } else if (element.attachEvent)
        {
            element.attachEvent("on" + type, handler);
        }
    },
    // 注销监听事件
    delEvent : function (element, type, handler) {
        if (element.removeEventListener)
        {
            element.removeEventListener(type, handler, false);
        } else if (element.detachEvent)
        {
            element.detachEvent("on" + type, handler);
        }
    }
}
var DragDrop = function () {
    // 判断DOM元素是否正在被拖动的标志
    var dragging = null;
    // DOM元素左上角与鼠标指针的差值
        diffX = 0;
        diffY = 0;
    function handleEvent(event) {
        event = EventUtil.getEvent(event);
        var target = EventUtil.getTarget(event);
        switch (event.type) {
            case "mousedown" : 
            // 判断DOM元素的class中是否含有draggable属性
                if (target.className.indexOf("draggable") > -1) {
                    dragging = target;
                    diffX = event.clientX - target.offsetLeft;
                    diffY = event.clientY - target.offsetTop;
                }
            break;

            case "mousemove" : 
                if (dragging != null) {
                    target.style.left = event.clientX - diffX + "px";
                    target.style.top = event.clientY - diffY + "px";
                }
            break;

            case "mouseup" :
                dragging = null;
            break;

        }
    }
    return {
        enable : function () {
            EventUtil.addEvent(document, "mousedown", handleEvent);
            EventUtil.addEvent(document, "mousemove", handleEvent);
            EventUtil.addEvent(document, "mouseup", handleEvent);
        },
        disable : function () {
            EventUtil.delEvent(document, "mousedown", handleEvent);
            EventUtil.delEvent(document, "mousemove", handleEvent);
            EventUtil.delEvent(document, "mouseup", handleEvent);
        }
    }
}();
DragDrop.enable();

这里需要讲解的是diffX和diffY,它们表示元素左上角与鼠标指针的差值。
diffX = 鼠标的x坐标 - 元素对象的offsetLeft
diffY = 鼠标的y坐标 - 元素对象的offsetTop
如下图所示:

上一篇下一篇

猜你喜欢

热点阅读