JavaScript implements mouse drag element instance code

Source: Internet
Author: User

  This article mainly introduces the JavaScript implementation mouse Drag element instance code, need friends can refer to the following

First, preface   The goal of the mouse drag element is to drag a lot of small dots on a page, for fixed positioning, and then in the copy HTML, pasted in the page development code, is such a function, realized many times, did not do a good job, Forced to use the JQuery.fn.draggable plug-in, in contact with some information and other people's ideas, today finally put the drag function to improve, the following to see its implementation     II, design ideas   in the drag element binding mouse press event, Binds the mouse movement in the document object, the mouse bounces the event; Why not bind three events to a drag element because the mouse moves and bounces the event handler will not execute     code as follows: $target. bind (' MouseDown ' , FN);   $ (document). Bind (' MouseMove ', fn). bind (' MouseUp ', FN);       III, source implementation details   in the implementation of the source code there are many need to pay attention to the place:   1, first in the mouse down event, when you click the drag element, you may select the area text, this is not what we need, the solution is as follows:     Code as follows://block text is 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 a picture (img tag), the mouse drag the picture a small distance, there will be a small hint, that is: The picture can not be dragged, this is the browser's default behavior, so long as the browser to prevent the default behavior can be     code as follows : E.preventdefault ();     3, questions about boundaries (handling drag ranges)   first implementation code is as follows:     code is as follows://X,y represents the Left,top value that the drag element will set, Limitobj is the drag Range object. The problem is found during the test,//during the drag process, the dragged object is sometimes not directly near the boundary &nbsP if (x >= limitobj._left && x <= limitobj._right) {    $target. css ({left:x + ' px '});} if (Y >= limitobj._top && y <= limitobj._bottom) {    $target. css ({top:y + ' px '});       Think further: why the problem arises because variable x may be less than limitobj._left or greater than limitobj._right, and variable y is the same, so the code needs to be handled like this: 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 the problem, but cloudgamer a better way:     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:   Code as follows: $.fn.extend ({   /** &NBsp    *   autor: Blog garden hua Zi yjh 2014/02/21      */    drag:function (options) {  &NB Sp     var dragstart, DragMove, Dragend,             $boundaryElem, limitobj;           function _initoptions () {            var noop = function () {}, defaultoptions;               defaultoptions = {//default configuration item             &NB Sp   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) {          &N Bsp var ClientX, ClientY, Offsetleft, offsettop,                 $target = $ (this), SE LF = this;               Limitobj = {                _lef t:0,                 _top:0,               &N Bsp _right: ($boundaryElem. innerwidth () | | | $ (window). Width ())-$target. Outerwidth (),           &NBS P     _bottom: ($boundaryElem. Innerheight () | | | $ (window). Height ())-$target. Outerheight ()       & nbsp    };              //record the position of mouse down and the relative position of drag element             ClientX = E.clientx;             ClientY = E.clienty;             offsetleft = This.offsetleft;             offsettop = this.offsettop;               dragstart.apply (this, arguments);             $ (document) bind (' MouseMove ', movehandle)           &NB Sp            . bind (' MouseUp ', uphandle);              //mouse mobile event handling             function Movehandle (e) {                var x = e.clientx-clientx + offsetleft     &NBS P           var y = e.clienty-clienty + offsettop;                   $target. css {            &NB Sp       Left:Math.max (math.min (x, Limitobj._right),  limitobj._left) + ' px ',       &NBS P   &NBSp         Top:Math.max (Math.min (y, Limitobj._bottom),  limitobj._top) + ' px '                });                   dragmove.apply (self, arguments);                //block browser default behavior (mouse drag picture a small distance, there will be a small hint of a ban, that is: pictures can not be dragged)     &NB Sp           E.preventdefault ();                          //mouse bounce event handling     &NB Sp       function Uphandle (e) {                $ (document). Unbind (' Mo Usemove ', movehandle);                 dragend.apply (self, arguments);                     {          _initoptions ( ); Initialize Configuration objects           $ (this)         CSS ({position: ' absolute '})        . each (function () {          &NB Sp $ (this). bind (' MouseDown ', function (e) {                _drag.apply (this, [E]); &NB Sp              //Blocking area text selected for Chrome Firefox IE9           &N Bsp     E.preventdefault ();                /for Firefox IE9 | | Less than IE9                 window.getselection? Window.getselection (). Removeallranges (): Document.selection.empty ();            });        });         return this;    }});       Instance call:     Code as follows://Invoke instance (function () {    $ ('. Drag-elem '). Drag ({    &NBS P   Boundaryelem: ' #boundary ',         Dragstart:function() {            $ (this). HTML (' <span> ready to drag </span> '). css ({zindex:2}). Siblings ( ). css ({zindex:1});        },         dragmove:function () {            var pos = $ (this). Position ();             $ (this). HTML (' <span> drag (' +  pos.left + ', ' + Pos.top + ') </SPAN&G t; ');        },         dragend:function () {            $ (this). HTML (' <span> drag End </span> ');                     {   }) }());  

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.