JavaScript 實現鼠標拖動元素


一、前言

最開始實現鼠標拖動元素的目的就是在一個頁面上拖動很多小圓點,用於固定定位,然后在復制HTML,粘貼在頁面的開發代碼中,就是這么一個功能,實現了很多遍,都沒有做好,不得已采用了jQuery.fn.draggable插件,在接觸一些資料和別人的思路,今天終於把這個拖動功能給完善了,下面就來看看它的實現

DEMO1:http://jsfiddle.net/Jj9qA/4/
DEMO2: http://jsfiddle.net/gUYdg/1/

 

二、設計思路

在拖動元素上綁定鼠標按下事件,在文檔對象中綁定鼠標移動,鼠標彈起事件;
為什么不把三個事件都綁定在拖動元素上,這是因為鼠標移動太快時,鼠標移動和彈起事件處理程序將不會執行

$target.bind('mousedown', fn);

$(document)
.bind('mousemove', fn)
.bind('mouseup', fn);

 

三、源碼實現細節

在實現源碼中有很多需要值得注意的地方:

1、首先在鼠標按下事件中,當單擊拖動元素中,可能會選擇區域文字,這並不是我們所需要的,解決方法如下:

// 阻止區域文字被選中 for chrome firefox ie9
e.preventDefault();
// for firefox ie9 || less than ie9
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();


2、如果拖動元素是圖片(img標簽),鼠標在拖動圖片一小段距離,會出現一個禁止的小提示,即:圖片不能再拖動,
這是瀏覽器的默認行為,因此只要阻止瀏覽器默認行為就可以了

e.preventDefault();


3、關於邊界(處理拖動范圍)的問題

一開始實現的代碼如下:

// x,y代表拖動元素將要設置的left,top值,limitObj為拖動區域范圍對象,測試時就發現問題,
// 在拖動過程中,拖動對象有時不能直接靠近邊界

if ( x >= limitObj._left && x <= limitObj._right ) {
    $target.css({ left: x + 'px' });
}
if ( y >= limitObj._top && y <= limitObj._bottom ) {
    $target.css({ top: y + 'px' });
}

 

進一步思考:為什么會出現上面問題,原因在於變量x可能會小於limitObj._left或大於limitObj._right,變量y同理,
因此代碼需要像下面這樣處理:

if (x < limitObj._left) {
    x = limitObj._left;
}
if (x > limitObj._right) {
    x = limitObj._right;
}
if (y < limitObj._top) {
    y = limitObj._top;
}
if (y > limitObj._bottom) {
    y = limitObj._bottom;
}
$target.css({ left: x + 'px', top: y + 'px' });

 

終於解決了這個問題,但是cloudgamer給出了更好的寫法:

$target.css({
    left: Math.max( Math.min(x, limitObj._right),  limitObj._left) + 'px',
    top: Math.max( Math.min(y, limitObj._bottom),  limitObj._top) + 'px'
});

 

完整程序源碼

$.fn.extend({
    /**
     *   Autor: 博客園華子yjh 2014/02/21
     */
    drag: function(options) {
        var dragStart, dragMove, dragEnd,
            $boundaryElem, limitObj;

        function _initOptions() {
            var noop = function(){}, defaultOptions;

            defaultOptions = { // 默認配置項
                boundaryElem: 'body' // 邊界容器
            };
            options = $.extend( defaultOptions, options || {} );
            $boundaryElem = $(options.boundaryElem);

            dragStart = options.dragStart || noop,
            dragMove = options.dragMove || noop,
            dragEnd = options.dragEnd || noop;
        }

        function _drag(e) {
            var clientX, clientY, offsetLeft, offsetTop,
                $target = $(this), self = this;

            limitObj = {
                _left: 0,
                _top: 0,
                _right: ($boundaryElem.innerWidth() || $(window).width()) - $target.outerWidth(),
                _bottom: ($boundaryElem.innerHeight() || $(window).height()) - $target.outerHeight()
            };
            
            // 記錄鼠標按下時的位置及拖動元素的相對位置
            clientX = e.clientX;
            clientY = e.clientY;
            offsetLeft = this.offsetLeft;
            offsetTop = this.offsetTop;
            
            dragStart.apply(this, arguments);
            $(document).bind('mousemove', moveHandle)
                        .bind('mouseup', upHandle);

            // 鼠標移動事件處理
            function moveHandle(e) {
                var x = e.clientX - clientX + offsetLeft;
                var y = e.clientY - clientY + offsetTop;
                
                $target.css({
                    left: Math.max( Math.min(x, limitObj._right),  limitObj._left) + 'px',
                    top: Math.max( Math.min(y, limitObj._bottom),  limitObj._top) + 'px'
                });

                dragMove.apply(self, arguments);
                // 阻止瀏覽器默認行為(鼠標在拖動圖片一小段距離,會出現一個禁止的小提示,即:圖片不能再拖動)
                e.preventDefault();
            }

            // 鼠標彈起事件處理
            function upHandle(e) {
                $(document).unbind('mousemove', moveHandle);
                dragEnd.apply(self, arguments);
            }
        }

        _initOptions(); // 初始化配置對象

        $(this)
        .css({ position: 'absolute' })
        .each(function(){
            $(this).bind('mousedown', function(e){
                _drag.apply(this, [e]);
                // 阻止區域文字被選中 for chrome firefox ie9
                e.preventDefault();
                // for firefox ie9 || less than ie9
                window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
            });
        });
        return this;
    }
});

實例調用:

// 調用實例
(function(){
    $('.drag-elem').drag({
        boundaryElem: '#boundary',
        dragStart: function(){
            $(this).html('<span>准備拖動</span>').css({ zIndex: 2 }).siblings().css({ zIndex: 1 });
        },
        dragMove: function(){
            var pos = $(this).position();
            $(this).html('<span>拖動中(' +  pos.left + ',' + pos.top + ')</span>' );
        },
        dragEnd : function(){
            $(this).html('<span>拖動結束</span>');            
        }
    });
}());

 

2014/03/02 源碼更新及demo:

$.fn.extend({
    /**
     *   Autor: 博客園華子yjh update 2014/03/02
     */
    drag: function(options) {
        var dragStart, dragMove, dragEnd,

            $boundaryElem, b_width, b_height,
            limitObj, isBeyond, diffX, diffY,

            win_width = $(window).width(),
            win_height = $(window).height();

        function _initOptions() {
            var noop = function(){}, defaultOptions;

            defaultOptions = {          // 默認配置項
                boundaryElem: 'body',   // 邊界容器
                isLimit: false          // 是否限制拖動范圍
            };
            options = $.extend( defaultOptions, options || {} );

            // 邊界元素及其寬高
            $boundaryElem = $(options.boundaryElem);
            b_width = $boundaryElem.innerWidth();
            b_height = $boundaryElem.innerHeight();

            dragStart = options.dragStart || noop,
            dragMove = options.dragMove || noop,
            dragEnd = options.dragEnd || noop;
        }

        function _drag(e) {
            var clientX, clientY, offsetLeft, offsetTop, width, height,
                $target = $(this), self = this;
            
            // 記錄鼠標按下時的位置及拖動元素的相對位置
            clientX = e.clientX;
            clientY = e.clientY;
            offsetLeft = this.offsetLeft;
            offsetTop = this.offsetTop;

            width = $target.outerWidth();
            height = $target.outerHeight();            

            limitObj = {
                _left: 0,
                _top: 0,
                _right: (b_width || win_width) - width,
                _bottom: (b_height || win_height) - height
            };
            
            // 拖動元素是否超出了限制邊界
            isBeyound = width > b_width && height > b_height;
            if (isBeyound) {
                diffX = b_width - width;
                diffY = b_height - height;
            }
            
            dragStart.apply(this, arguments);
            $(document).bind('mousemove', moveHandle)
                        .bind('mouseup', upHandle);

            // 鼠標移動事件處理
            function moveHandle(e) {
                var e_diffX = e.clientX - clientX,
                    e_diffY = e.clientY - clientY,
                    x = e_diffX + offsetLeft,
                    y = e_diffY + offsetTop;

                if (options.isLimit && !isBeyound) {
                    x = Math.max( Math.min(x, limitObj._right),  limitObj._left );
                    y = Math.max( Math.min(y, limitObj._bottom),  limitObj._top );
                }

                if (options.isLimit && isBeyound) {
                    x = e_diffX < 0 ? Math.max(x, diffX) : Math.min(x, 0);
                    y = e_diffY < 0 ? Math.max(y, diffY) : Math.min(y, 0);
                }

                $target.css({
                    left: x + 'px',
                    top: y + 'px'
                });

                dragMove.apply(self, arguments);
                // 阻止瀏覽器默認行為(鼠標在拖動圖片一小段距離,會出現一個禁止的小提示,即:圖片不能再拖動)
                e.preventDefault();
            }

            // 鼠標彈起事件處理
            function upHandle(e) {
                $(document).unbind('mousemove', moveHandle);
                dragEnd.apply(self, arguments);
            }
        }

        _initOptions(); // 初始化配置對象

        $(this)
        .css({ position: 'absolute' })
        .each(function(){
            $(this).bind('mousedown', function(e){
                if ($(this).data('data-resize')) {
                    return;
                }
                _drag.apply(this, [e]);
                // 阻止區域文字被選中 for chrome firefox ie9
                e.preventDefault();
                // for firefox ie9 || less than ie9
                window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
            });
        });
        return this;
    }
});
View Code

demo:http://jsfiddle.net/aTB2H/

 

PS: 如有描述錯誤,請幫忙指正,如果你們有不明白的地方也可以發郵件給我,

  如需轉載,請附上本文地址及出處:博客園華子yjh,謝謝!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM