问问题
227 次
1 回答
1
var draggable = function(element) {
element.addEventListener('mousedown', function(e) {
e.stopPropagation();
// if the current target is different (in the case of a child node), don't drag.
// you can customize this to specify types of children which prevent dragging
if (e.target != element)
return;
var offsetX = e.pageX - element.offsetLeft;
var offsetY = e.pageY - element.offsetTop;
function move(e) {
element.style.left = (e.pageX - offsetX) + 'px';
element.style.top = (e.pageY - offsetY) + 'px';
}
function stop(e) {
// remove the event listeners on the document when not dragging
document.removeEventListener('mousemove', move);
document.removeEventListener('mouseup', stop)
}
document.addEventListener('mousemove', move)
document.addEventListener('mouseup', stop)
})
}
function init() {
var ele = document.getElementById('ele');
draggable(ele)
}
这在某些 IE 版本中可能不起作用,但您应该能够为此添加必要的修复程序。这是小提琴http://jsfiddle.net/seKbz/2/
于 2012-07-17T05:31:33.433 回答