JavaScript code _ javascript

Source: Internet
Author: User
This article mainly introduces the JavaScript implementation of the mouse drag element instance code. For more information, see I. Preface

The purpose of dragging an element with the mouse is to drag a lot of dots on a page for fixed positioning, and then copy HTML and paste it in the development code of the page. This is such a function, it has been implemented many times and has not been done well. jQuery has to be used. fn. the draggable plug-in has been updated with some materials and other people's ideas. Today, the drag function has been improved. Let's take a look at its implementation.


Ii. Design Ideas

Bind the mouse-down event to the drag element, move the mouse in the document object, and hover the mouse over the event;
Why not bind all three events to the drag element? This is because when the mouse moves too fast, the event handler will not execute

The Code is as follows:


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

$ (Document)
. Bind ('mousemove ', fn)
. Bind ('mouseup', fn );

Iii. Source Code Implementation Details

There are many noteworthy points in the Implementation source code:

1. When you press the mouse over the event, when you click the drag element, the area text may be selected. This is not what we need. The solution is as follows:

The Code is as follows:


// Prevent the 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 drag element is an image (img label) and the mouse is dragging the image for a short distance, a small forbidden prompt is displayed, that is, the image cannot be dragged,
This is the default behavior of the browser, so you only need to block the default behavior of the browser.

The Code is as follows:


E. preventDefault ();

3. Boundary (processing the drag range)

The first implementation code is as follows:

The Code is as follows:


// X and y represent the left and top values to be set for the drag element. limitObj is the drag range object. problems are found during the test,
// During dragging, objects cannot be directly near the border.

If (x> = limitObj. _ left & x <= limitObj. _ right ){
Export target.css ({left: x + 'px '});
}
If (y> = limitObj. _ top & y <= limitObj. _ bottom ){
Export target.css ({top: y + 'px '});
}

Further Thinking: Why is the above problem? The reason is that the variable x may be smaller than limitObj. _ left or greater than limitObj. _ right. The variable y is the same,
Therefore, the code needs to be processed as follows:

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;
}
Export target.css ({left: x + 'px ', top: y + 'px '});

This problem was finally solved, but cloudgamer provided a better way:

The Code is as follows:


Export 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:

The Code is as follows:


$. Fn. extend ({
/**
* Autor: huazi yjh 44/02/21
*/
Drag: function (options ){
Var dragStart, dragMove, dragEnd,
$ BoundaryElem, limitObj;

Function _ initOptions (){
Var noop = function () {}, defaultOptions;

DefaultOptions = {// default configuration item
BoundaryElem: 'body' // boundary container
};
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 ()
};

// Record the position when the mouse is pressed and the relative position of the drag Element
ClientX = e. clientX;
ClientY = e. clientY;
OffsetLeft = this. offsetLeft;
OffsetTop = this. offsetTop;

DragStart. apply (this, arguments );
$ (Document). bind ('mousemove ', moveHandle)
. Bind ('mouseup', upHandle );

// Handle mouse movement events
Function moveHandle (e ){
Var x = e. clientX-clientX + offsetLeft;
Var y = e. clientY-clientY + offsetTop;

Export 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 );
// Prevent the default behavior of the browser (if you move the mouse to a short distance from the image, a small forbidden prompt will appear, that is, the image cannot be dragged)
E. preventDefault ();
}

// Handle the event with the mouse popping up
Function upHandle (e ){
$ (Document). unbind ('mousemove ', moveHandle );
DragEnd. apply (self, arguments );
}
}

_ InitOptions (); // initialize the configuration object

$ (This)
. Css ({position: 'absolute '})
. Each (function (){
$ (This). bind ('mousedown ', function (e ){
_ Drag. apply (this, [e]);
// Prevent the 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 ();
});
});
Return this;
}
});

Instance call:

The Code is as follows:


// Call an instance
(Function (){
$ ('. Drag-elem'). drag ({
BoundaryElem: '# boundary ',
DragStart: function (){
((This).html('{drag '}.css ({zIndex: 2 }).siblings().css ({zIndex: 1 });
},
DragMove: function (){
Var pos = $ (this). position ();
(This).html ('dragging ('+ pos. left +', '+ pos. top + ')');
},
DragEnd: function (){
Optional (this).html ('drag to terminate ');
}
});
}());

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.