JavaScript simple Mouse Drag instance: Automatic adsorption instance

Source: Internet
Author: User
Tags add key range return

Article Introduction: JavaScript Mouse drag + automatic adsorption instance.

After a few days of learning JavaScript, I did a simple mouse drag instance, the drag process in the section automatically detect the distance with the target container, within a certain distance can automatically be dragged elements into the target container, I hope to start learning JavaScript children's shoes useful ...

Take a look at the effect chart (Chrome, FireFox, Opera, Safari, IE9 test pass):

Effect Chart (dashed box: target object Blue fill transparent box: Temporarily drag object red fill box: Dragged object)

main idea : First, add a mouse down (MouseDown) event to the div you want to drag, add a mouse movement (MouseMove) event to the Document object, and a mouse bounce (MouseUp) event. When the mouse starts to move, create a temporary drag object (temp), change the position of the temporary drag target during the move, set the position of the dragged Div (elem) to the location of the temporary drag target temp When the mouse is released, and then remove the temporary drag target. During the move, it also detects the position relationship between the dragged object and the target Div, if the collision (you can set the scope of the adsorption), then the automatic adsorption (the dragged object into the target object), you need to explain: here for simplicity, and did not really put the dragged object into the target object, Simply sets the position of the dragged object.

when the mouse is pressed : Gets the position of the dragged element and the position of the mouse down, set the drag flag (Isdrag) value to True.

Elem.onmousedown = function (event) {//mouse down
            Isdrag = true;
            StartX = parseint (This.style.leftgetCSSValue (this, ' left '));
            Starty = parseint (This.style.topgetCSSValue (this, top));
            MX = Event.pagex;
            my = Event.pagey;
        };

when the mouse is moved : If Isdrag is true and the Temp object does not exist, the Temp object is created and the location of the temp is computed and set according to the mouse position.

Document.onmousemove = function (event) {//mouse move this.innerhtml = "Mouse Position (" +event.pagex+ "," +event.pagey+ "
            )"; if (Isdrag) {//is currently moving if (temp = undefined) {//temp Temporary drag target does not exist TEMP = Document.createelemen
                    T ("div");
                    Temp.id = "drag";
                    Temp.classname = "temp"; Document.body.appendChild (temp);//Add temp temporary drag target to page}//Change position Temp.style.le
                FT = (startx + event.pagex-mx) + "px";
                Temp.style.top = (Starty + event.pagey-my) + "px"; Detects if (Checkintersect (temp,$ ("target"), 20) in the target range {//within range $ ("Ta
                    Rget "). Style.border =" 2px #F00 dashed "; $ ("target"). Style.webkitanimationname = "light";//Flashing animation $ ("target"). style.webkitanimationduration = "1s
                    ";
  $ ("target"). Style.webkitanimationdelay = "0.5s";                  $ ("target"). Style.webkitanimationiterationcount = "100";
                    }else{//Not in range $ ("target"). Style.border = "2px #09F dashed";
                $ ("target"). Style.webkitanimationname = ""; }
            }
        };

description : The MouseMove event here is not added to the dragged object (elem), if added to the Elem, then if the mouse moved too fast once the mouse left the Elem object, then there will be problems.

Mouse Release : Detect collision results, set the position of the dragged object (elem) According to the situation, if the collision, according to the location of the target Div set the position of the dragged object (elem), otherwise, according to the location of the temp to set the location of the dragged object (Elem);

Document.onmouseup = function () {//mouse to release
            Isdrag = false;
            if (Checkintersect (temp,$ ("target")) {elem.style.left=$ ("target")
                . offsetleft+ "px";
                elem.style.top=$ ("target"). offsettop+ "px";
                
            } else{
                elem.style.left=temp.offsetleft+ "px";
                elem.style.top=temp.offsettop+ "px";
            }
            Document.body.removeChild (temp);//Move out the temporary drag target
            temp = null;
            $ ("target"). Style.border = "2px #09F dashed";
            $ ("target"). Style.webkitanimationname = "";//Cancel flashing
        };

=======================================================

Other functions to use: In the design process, we need perhaps some value of an element style, and if we adopt inline (which is written in the style attribute in the element tag), we can use a syntax like "obj.style.left" to perhaps, But if our style is inline (write CSS between

function Getcssvalue (Obj,key) {//Get element CSS value
        if (obj.currentstyle) {//ie return
            Obj.currentstyle[key];    
        } else{//! IE return
            Document.defaultView.getComputedStyle (obj,null) [key];
        }
    }

In addition, the detection of collision function;

function Checkintersect (obj1,obj2,distance) {//Collision detection, distance for adsorption range
var left1 = Obj1.offsetleft;
var top1 = obj1.offsettop;
var left2 = Obj2.offsetleft;
var top2 = obj2.offsettop;
var width1 = obj1.offsetwidth;
var height1 = obj1.offsetheight;
var width2 = obj2.offsetwidth;
var height2 = obj2.offsetheight;
Return (
((left1-left2>=0&&left1-left2<width2+distance)
(left2-left1>=0&&left2-left1<width1+distance)) &&
((top1-top2>=0&&top1-top2(top2-top1>=0&&top2-top1);
}

Summary: Here is the main use of JavaScript mouse events, simple DOM node operations, as well as CSS3 of some new things, such as animation (animation), Fillet (Border-radius), Shadow (Box-shadow) and other knowledge.

Complete code: Click Download To download a



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.