Home >Web Front-end >JS Tutorial >JavaScript implementation of mouse drag element example code_javascript skills

JavaScript implementation of mouse drag element example code_javascript skills

WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWB
WBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOYWBOriginal
2016-05-16 16:58:351011browse

1. Foreword

The first purpose of implementing mouse dragging elements is to drag many small dots on a page for fixed positioning, and then copy the HTML and paste it into the development code of the page. This is such a function, and it has achieved a lot I have done it all over the place, but I have no choice but to use the jQuery.fn.draggable plug-in. After contacting some information and other people’s ideas, I finally perfected this dragging function today. Let’s take a look at its implementation


2. Design Ideas

Bind the mouse down event to the drag element, bind the mouse movement and mouse up events to the document object;
Why not bind all three events to the drag element? This is because Mouse move and pop up event handlers will not execute when the mouse moves too fast

Copy code The code is as follows:

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

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

3. Source code implementation details

There are many things worth noting in the implementation source code:

1. First, in the mouse press event, when clicking and dragging the element, the area text may be selected. This is not what we need. The solution is as follows:

Copy code The code is as follows:

// Prevent area text from being selected for chrome firefox ie9
e.preventDefault();
// for firefox ie9 || less than ie9
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();

2. If the dragging element is a picture (img tag) and the mouse drags the picture a short distance, a small forbidden prompt will appear, that is: the picture cannot be dragged anymore.
This is the browser's default behavior, so just block the browser default behavior

Copy code The code is as follows:

e.preventDefault();

3. Issues about boundaries (handling drag range)

The code implemented at the beginning is as follows:

Copy code The code is as follows:

// x, y represent the values ​​that will be set by dragging the element The left, top values, and limitObj are the dragging area objects. The problem was discovered during testing,
// During the dragging process, the dragging object sometimes cannot be directly close to the boundary

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

Further thinking: Why does the above problem occur? The reason is that the variable x may be smaller than limitObj._left or larger than limitObj._right. The same is true for the variable y.
So the code needs to be processed as follows:

Copy code The code is as follows:

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' });

Finally solved this problem, but cloudgamer gave a better way of writing:

Copy code The code is as follows:

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

Complete program source code:

Copy code The code is as follows:

$.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();
                                                                                                                                                                                              );

}

}

_initOptions(); // Initialize the configuration object

$(this)
.css({ position: 'absolute' })

.each(function(){

$(this).bind('mousedown', function(e){

          _drag.apply(this, [e]);

                                                                                                                                         // for firefox ie9 || less than ie9
                window.getSelection? window.getSelection().                        AllRanges(): document.selection.empty();                                            ; 🎜> });



Instance call:





Copy code


The code is as follows:

// Call instance

(function(){

$('.drag-elem').drag({

boundaryElem: '#boundary', dragStart: function(){ $(this).html(' Prepare to drag').css({ zIndex: 2 }).siblings().css({ zIndex: 1 });     },     dragMove: function(){ var pos = $ (this).position(); ; },
dragEnd : function(){
$(this).html('Drag end'); }) ;
}());


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn