我有一系列固定高度和宽度的按钮,这些按钮需要可拖动并且可以在父div内的任何位置放置。
根据客户端的要求,我不能使用任何外部库,嗯...我可以在几秒钟内用jQuery做到这一点但是,我想这是它的一个缺点:你不能学习更多基本的东西。 ..
我该怎么做呢?这个问题就是那些按钮位于一个也可以拖动的div里面,所以我需要注意定位,我只能使用相对。
我有什么想法可以去做吗?提前谢谢。
答案 0 :(得分:0)
Peter-Paul Koch写了excellent how-to on drag and drop。我只记得自己编写自己的3/4,所以我wrapped that up in a fiddle。
function makeDraggable(draggable, container){
// In case you don't want to have a container
var container = container || window;
// So we know what to do on mouseup:
// At this point we're not sure the user wants to drag
var dragging = false;
// The movement listener and position modifier
function dragHandler(moveEvent){
moveEvent.preventDefault();
dragging = true;
// Ascertain where the mouse is
var coordinates = [
moveEvent.clientX,
moveEvent.clientY
];
// Style properties we need to apply to the element
var styleValues = {
position : 'absolute',
left : coordinates[0] + 'px',
top : coordinates[1] + 'px'
};
// Apply said styles
for(property in styleValues){
if(styleValues.hasOwnProperty(property)){
draggable.style[property] = styleValues[property];
}
}
}
function dropHandler(upEvent){
// Only interfere if we've had a drag event
if(dragging === true){
// We don't want the button click event to fire!
upEvent.preventDefault();
// We don't want to listen for drag and drop until this is clicked again
container.removeEventListener('mousemove', dragHandler, false);
draggable.removeEventListener('mouseup', dropHandler, false);
dragging = false;
}
}
// Where all the fun happens
draggable.addEventListener('mousedown', function dragListener(downEvent){
downEvent.preventDefault();
// The drag event
container.addEventListener('mousemove', dragHandler, false);
// The end of drag, if dragging occurred
draggable.addEventListener('mouseup', dropHandler, false);
}, false);
}