首页 > 代码库 > 原生拖放代码

原生拖放代码

这段js代码会让页面所有position:absolute;的元素可以拖动

var chef = (function(){
        var drawDiv,ofstX,ofstY;

        function fun(event){
            var event = event || window.event;
            var target = event.target || event.srcElement;
            switch(event.type){
                case "mousedown":
                            drawDiv = target;
                            ofstX = event.clientX-drawDiv.offsetLeft;
                            ofstY = event.clientY-drawDiv.offsetTop;
                    break;
                case "mousemove":
                        if(drawDiv != null){
                            drawDiv.style.left = event.clientX - ofstX + "px";
                            drawDiv.style.top = event.clientY - ofstY + "px";
                        }
                    break;
                case "mouseup":
                    drawDiv = null;
                    break;

            }
        };

        document.body.onmousedown = function(event){fun(event);};
        document.body.onmousemove = function(event){fun(event);};
        document.body.onmouseup   = function(event){fun(event);};
    })();

原生拖放代码