js drag and drop drag and drop

2011-01-07  来源:本站原创  分类:Web  人气:166 

Good tutorial http://www.webreference.com/programming/javascript/mk/column2/3.html

// iMouseDown represents the current mouse button state: up or down
/*
lMouseState represents the previous mouse button state so that we can
check for button clicks and button releases:

if(iMouseDown && !lMouseState) // button just clicked!
if(!iMouseDown && lMouseState) // button just released!
*/
var mouseOffset = null;
var iMouseDown  = false;
var lMouseState = false;
var dragObject  = null;

// Demo 0 variables
var DragDrops   = [];
var curTarget   = null;
var lastTarget  = null;
var dragHelper  = null;
var tempDiv     = null;
var rootParent  = null;
var rootSibling = null;

Number.prototype.NaN0=function(){return isNaN(this)?0:this;}

function CreateDragContainer(){
        /*
        Create a new "Container Instance" so that items from one "Set" can not
        be dragged into items from another "Set"
        */
        var cDrag        = DragDrops.length;
        DragDrops[cDrag] = [];

        /*
        Each item passed to this function should be a "container".  Store each
        of these items in our current container
        */
        for(var i=0; i<arguments.length; i++){
                var cObj = arguments[i];
                DragDrops[cDrag].push(cObj);
                cObj.setAttribute('DropObj', cDrag);

                /*
                Every top level item in these containers should be draggable.  Do this
                by setting the DragObj attribute on each item and then later checking
                this attribute in the mouseMove function
                */
                for(var j=0; j<cObj.childNodes.length; j++){

                        // Firefox puts in lots of #text nodes...skip these
                        if(cObj.childNodes[j].nodeName=='#text') continue;

                        cObj.childNodes[j].setAttribute('DragObj', cDrag);
                }
        }
}

function mouseMove(ev){
        ev         = ev || window.event;

        /*
        We are setting target to whatever item the mouse is currently on

        Firefox uses event.target here, MSIE uses event.srcElement
        */
        var target   = ev.target || ev.srcElement;
        var mousePos = mouseCoords(ev);

        // mouseOut event - fires if the item the mouse is on has changed
        if(lastTarget && (target!==lastTarget)){
                // reset the classname for the target element
                var origClass = lastTarget.getAttribute('origClass');
                if(origClass) lastTarget.className = origClass;
        }

        /*
        dragObj is the grouping our item is in (set from the createDragContainer function).
        if the item is not in a grouping we ignore it since it can't be dragged with this
        script.
        */
        var dragObj = target.getAttribute('DragObj');

         // if the mouse was moved over an element that is draggable
        if(dragObj!=null){

                // mouseOver event - Change the item's class if necessary
                if(target!=lastTarget){
                        var oClass = target.getAttribute('overClass');
                        if(oClass){
                                target.setAttribute('origClass', target.className);
                                target.className = oClass;
                        }
                }

                // if the user is just starting to drag the element
                if(iMouseDown && !lMouseState){
                        // mouseDown target
                        curTarget     = target;

                        // Record the mouse x and y offset for the element
                        rootParent    = curTarget.parentNode;
                        rootSibling   = curTarget.nextSibling;

                        mouseOffset   = getMouseOffset(target, ev);

                        // We remove anything that is in our dragHelper DIV so we can put a new item in it.
                        for(var i=0; i<dragHelper.childNodes.length; i++) dragHelper.removeChild(dragHelper.childNodes[i]);

                        // Make a copy of the current item and put it in our drag helper.
                        dragHelper.appendChild(curTarget.cloneNode(true));
                        dragHelper.style.display = 'block';

                        // set the class on our helper DIV if necessary
                        var dragClass = curTarget.getAttribute('dragClass');
                        if(dragClass){
                                dragHelper.firstChild.className = dragClass;
                        }

                        // disable dragging from our helper DIV (it's already being dragged)
                        dragHelper.firstChild.removeAttribute('DragObj');

                        /*
                        Record the current position of all drag/drop targets related
                        to the element.  We do this here so that we do not have to do
                        it on the general mouse move event which fires when the mouse
                        moves even 1 pixel.  If we don't do this here the script
                        would run much slower.
                        */
                        var dragConts = DragDrops[dragObj];

                        /*
                        first record the width/height of our drag item.  Then hide it since
                        it is going to (potentially) be moved out of its parent.
                        */
                        curTarget.setAttribute('startWidth',  parseInt(curTarget.offsetWidth));
                        curTarget.setAttribute('startHeight', parseInt(curTarget.offsetHeight));
                        curTarget.style.display  = 'none';

                        // loop through each possible drop container
                        for(var i=0; i<dragConts.length; i++){
                                with(dragConts[i]){
                                        var pos = getPosition(dragConts[i]);

                                        /*
                                        save the width, height and position of each container.

                                        Even though we are saving the width and height of each
                                        container back to the container this is much faster because
                                        we are saving the number and do not have to run through
                                        any calculations again.  Also, offsetHeight and offsetWidth
                                        are both fairly slow.  You would never normally notice any
                                        performance hit from these two functions but our code is
                                        going to be running hundreds of times each second so every
                                        little bit helps!

                                        Note that the biggest performance gain here, by far, comes
                                        from not having to run through the getPosition function
                                        hundreds of times.
                                        */
                                        setAttribute('startWidth',  parseInt(offsetWidth));
                                        setAttribute('startHeight', parseInt(offsetHeight));
                                        setAttribute('startLeft',   pos.x);
                                        setAttribute('startTop',    pos.y);
                                }

                                // loop through each child element of each container
                                for(var j=0; j<dragConts[i].childNodes.length; j++){
                                        with(dragConts[i].childNodes[j]){
                                                if((nodeName=='#text') || (dragConts[i].childNodes[j]==curTarget)) continue;

                                                var pos = getPosition(dragConts[i].childNodes[j]);

                                                // save the width, height and position of each element
                                                setAttribute('startWidth',  parseInt(offsetWidth));
                                                setAttribute('startHeight', parseInt(offsetHeight));
                                                setAttribute('startLeft',   pos.x);
                                                setAttribute('startTop',    pos.y);
                                        }
                                }
                        }
                }
        }

        // If we get in here we are dragging something
        if(curTarget){
                // move our helper div to wherever the mouse is (adjusted by mouseOffset)
                dragHelper.style.top  = mousePos.y - mouseOffset.y;
                dragHelper.style.left = mousePos.x - mouseOffset.x;

                var dragConts  = DragDrops[curTarget.getAttribute('DragObj')];
                var activeCont = null;

                var xPos = mousePos.x - mouseOffset.x + (parseInt(curTarget.getAttribute('startWidth')) /2);
                var yPos = mousePos.y - mouseOffset.y + (parseInt(curTarget.getAttribute('startHeight'))/2);

                // check each drop container to see if our target object is "inside" the container
                for(var i=0; i<dragConts.length; i++){
                        with(dragConts[i]){
                                if(((getAttribute('startLeft'))                               < xPos) &&
                                        ((getAttribute('startTop'))                                < yPos) &&
                                        ((getAttribute('startLeft') + getAttribute('startWidth'))  > xPos) &&
                                        ((getAttribute('startTop')  + getAttribute('startHeight')) > yPos)){

                                                /*
                                                our target is inside of our container so save the container into
                                                the activeCont variable and then exit the loop since we no longer
                                                need to check the rest of the containers
                                                */
                                                activeCont = dragConts[i];

                                                // exit the for loop
                                                break;
                                }
                        }
                }

                // Our target object is in one of our containers.  Check to see where our div belongs
                if(activeCont){
                        // beforeNode will hold the first node AFTER where our div belongs
                        var beforeNode = null;

                        // loop through each child node (skipping text nodes).
                        for(var i=activeCont.childNodes.length-1; i>=0; i--){
                                with(activeCont.childNodes[i]){
                                        if(nodeName=='#text') continue;

                                        // if the current item is "After" the item being dragged
                                        if(
                                                curTarget != activeCont.childNodes[i]                              &&
                                                ((getAttribute('startLeft') + getAttribute('startWidth'))  > xPos) &&
                                                ((getAttribute('startTop')  + getAttribute('startHeight')) > yPos)){
                                                        beforeNode = activeCont.childNodes[i];
                                        }
                                }
                        }

                        // the item being dragged belongs before another item
                        if(beforeNode){
                                if(beforeNode!=curTarget.nextSibling){
                                        activeCont.insertBefore(curTarget, beforeNode);
                                }

                        // the item being dragged belongs at the end of the current container
                        } else {
                                if((curTarget.nextSibling) || (curTarget.parentNode!=activeCont)){
                                        activeCont.appendChild(curTarget);
                                }
                        }

                        // make our drag item visible
                        if(curTarget.style.display!=''){
                                curTarget.style.display  = '';
                        }
                } else {

                        // our drag item is not in a container, so hide it.
                        if(curTarget.style.display!='none'){
                                curTarget.style.display  = 'none';
                        }
                }
        }

        // track the current mouse state so we can compare against it next time
        lMouseState = iMouseDown;

        // mouseMove target
        lastTarget  = target;

        // track the current mouse state so we can compare against it next time
        lMouseState = iMouseDown;

        // this helps prevent items on the page from being highlighted while dragging
        return false;
}

function mouseUp(ev){
        if(curTarget){
                // hide our helper object - it is no longer needed
                dragHelper.style.display = 'none';

                // if the drag item is invisible put it back where it was before moving it
                if(curTarget.style.display == 'none'){
                        if(rootSibling){
                                rootParent.insertBefore(curTarget, rootSibling);
                        } else {
                                rootParent.appendChild(curTarget);
                        }
                }

                // make sure the drag item is visible
                curTarget.style.display = '';
        }
        curTarget  = null;
        iMouseDown = false;
}

function mouseDown(){
        iMouseDown = true;
        if(lastTarget){
                return false;
        }
}

document.onmousemove = mouseMove;
document.onmousedown = mouseDown;
document.onmouseup   = mouseUp;

window.onload = function(){
        // Create our helper object that will show the item while dragging
        dragHelper = document.createElement('DIV');
        dragHelper.style.cssText = 'position:absolute;display:none;';

        CreateDragContainer(
                document.getElementById('DragContainer1'),
                document.getElementById('DragContainer2'),
                document.getElementById('DragContainer3')
        );

        document.body.appendChild(dragHelper);
}
相关文章
  • js to achieve simple drag and drop 2010-09-25

    The simplest implementation of js said drag and drop drag and drop, and now major, medium and small sites are essentially similar things, especially for pop-up layer drag, it is common mess. . . In fact, for pop-up layer, the initial aim is very simp

  • Eclipse drag and drop (Drag and Drop) (change) 2010-04-01

    Operating system is the most commonly used drag and drop movement of files to copy, drag and drop increased use of simple software. SWT also supports drag and drop, but more complicated programming. Figure 18.1 Schematic diagram of the realization of

  • js drag and drop drag and drop 2011-01-07

    Good tutorial http://www.webreference.com/programming/javascript/mk/column2/3.html // iMouseDown represents the current mouse button state: up or down /* lMouseState represents the previous mouse button state so that we can check for button clicks an

  • drop user cascade drop user and the difference between 2010-10-19

    drop user; just delete the user, drop user × × cascade; will delete the user name and view all the tables. user Specify the user to be dropped. Oracle Database does not drop users whose schemas contain objects unless you specify CASCADE or unless you

  • drop user and drop user cascade difference 2010-10-19

    drop user; just delete the user, drop user × × cascade; will delete the user name of all tables and views. user Specify the user to be dropped. Oracle Database does not drop users whose schemas contain objects unless you specify CASCADE or unless you

  • Js popup (supports drag and drop, multiple pop automatically switch level) 2011-01-09

    Js popup Usage: 1, first import the css and js <script type="text/javascript" src="js/PopUpManager-compressed.js" ></script> <link href="css/PopUpLayer.css" type="text/css" rel="stylesheet"/

  • [Change] javascript Drag and Drop 2010-03-30

    <html> <head> <title> Drag-and-drop effect </title> <style> #idContainer{ border:10px solid #990000; width:600px; height:300px; } #idDrag{ border:5px solid #C4E3FD; background:#C4E3FD; width:50px; height:50px; margin:50px; }

  • Flex 3 Getting Started (18): Building an advanced user interface, drag and drop support added 2010-08-26

    In a typical visual development environment, you can select in the application and drag an object moving back and forth on the screen. Flex Drag and Drop Manager allows users to select an object, such as an element of List control, or a control such

  • Flex using drag and drop 2010-09-05

    All Flex components support drag and drop, some subset of the components also drag and drop with other functions, as these components can be achieved adding a property to drag and drop. Achieved in the Flex drag and drop in the use of drag and drop m

  • flex drag and drop operation (b) 2010-11-04

    Easier to make money at home Manually add the drag-and-drop support In the last article in Flex, you already know there are some controls built-in drag-and-drop operations support, and relatively easy to achieve, but often have to complete this opera

  • JS drag the container tools 2010-08-15

    var isIE = (document.all)? true: false; var $ = function (id) (return "string" == typeof id? document.getElementById (id): id;); var Class = (create: function () (return function () (this.initialize.apply (this, arguments);))) var Extend = funct

  • js drag the table out to achieve, to change column width 2010-04-13

    Read some on the table two days dragging out the js code, fear forgotten, Tie Shanglai arrayed. First, this aspect should be better on the compatible, but drag the mouse respond to the events it was not too: <! DOCTYPE html PUBLIC "- / / W3C / / D

  • asp.net + javascript + css (imitating the drag google personalized page layout) 2009-04-14

    Comparing the content of many, the main are javascript code, the code from Tin's are on the google and under get better Translation: His blog http://www.blogjava.net/iamtin And I used the database to preserve the layout of the framework, procedures u

  • jquery drag effect layer implementations 2010-11-28

    jquery layer drag effect of the implementation methods: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml&q

  • jquery image crop preview, simply drag 2010-11-29

    See the online image crop, it is a feeling, based on my own jquery-ui, and then clip it is generally accepted principles, implementation of a simple preview To the entire page, on the whole do not know how. // JavaScript Document var x; var y; var pr

  • DROP TABLESPACE when the data file is automatically deleted 2010-03-29

    DROP TABLESPACE when the data file is automatically deleted OMF OMF and non-management in the DROP TABLESPACE data files will automatically deleted when doing the test: SQL> alter system set db_create_file_dest = '/ oradata / data / standby' scope =

  • SQL Advanced usage constraints, Alter, Create, Drop 2010-06-22

    SQL PRIMARY KEY constraint PRIMARY KEY constraint to uniquely identify each record in a database table. Primary key must contain unique values. Primary key column can not contain NULL values. Each table should have a primary key, and each table can h

  • Oracle: drop user xx and drop user xx cascade difference 2011-05-19

    Oracle: drop user xx and drop user xx cascade of differences: SQL> drop user xx; drop user xx * ERROR at line 1: ORA-01922: CASCADE must be specified to remove the 'xx' SQL> drop user xx cascade; The user has discarded. ] [Explained drop user xx Spe

  • drop table dept cascade constraints 2011-08-02

    My colleagues asked me drop table dept cascade constraints; keyword cascade constraints of the role. Should exist in parent-child table foreign key when the parent table when the cascading drop drop the child table's foreign key. Simply records the t

  • Oracle Flashback Flashback - restore error DML, DDL (Drop) operation 2010-12-22

    Human error is the failure of the database system is one important reason, according to the survey about 40% of the system is operational errors or user errors caused by human error and these are particularly difficult to avoid. Traditionally taken i