Drag and drop is a very cool feature in the browsers too, if really needed. Most JS libraries has this functionality, from jQuery to MooTools. But how they do it?
Well, it's not black magic, actually really simple.
The idea
You need to combine two different mouse events: mouseDown and mouseMove, then track the mouse position, update an elements position, finally cancel the mouseMove event on mouseUp.
The goal
Create a freely movable window that you can move with a handle.
Click "read more" to see the codes.
The codes
This is the HTML markup.
CSS styles:Drag me
#todrag{
position: absolute;
left: 100px;
top: 10px;
color: #0f0;
background: #000;
width: 200px;
height: 100px;
}
#todrag span{
display: block;
position: relative;
left: 1px;
top: 1px;
width: 190px;
height: 20px;
background: #333;
padding: 4px;
cursor: move;
}
JavaScript code
var win = document.getElementById('todrag');
var handle = document.getElementById('handle');
handle.onmousedown = function(e)
{
// This is where you have to handle browser exceptions
var diffX = parseInt(win.style.left) - e.clientX;
var diffY = parseInt(win.style.top) - e.clientY;
// The mouseMove event is tracked, when the mouse button is down.
document.onmousemove = function(x)
{
win.style.left = x.clientX + diffX +'px';
win.style.top = x.clientY + diffY +'px';
}
}
/**
* Cancel the mouseMove event
*/
handle.onmouseup = function(e){
document.onmousemove = function(){}
}
This is it.File attached to post: simple-drag-n-drop.zip
Ehhez igen hasonlatos egy drag-n-drop megoldás, amit a jQuery megoldás. De ez lényegesen kevesebb és okosabb megoldás.
Ezt egy inntelligens kezelő "konténer" megoldással egész érdekes shop megoldásokat is lehetne belőle csinálni. :)
Szia Cyrus,
Igen, ez egy nagyon buta, nagyon fapados megoldás, a dolog célja az volt, hogy bemutassam, hogyan működik a drag and drop az alapjait tekintve, a fenti módszer még explorerben sem megy ;)
UPD: Tervezem amúgy megírni ennek a folytatásást, extra opciók hozzáadásást, objektumba való csomagolását.
All rights reserved, ©2008-2010 - Built on CodeIgniter framework - Konami codes - Mostly Valid XHTML 1.1 - Valid CSS 2.1