下面的代码尝试使img成为可拖动的(关于this),它可以工作,但是如果img移动所有包裹drag_wp
一起移动,我无法想象如何制作。 http://jsfiddle.net/cAeKG/8/有什么建议吗?
JS
function enableDraggin(el){
var dragging = dragging || false, x, y, ox, oy, current;
el.onmousedown = function(e){
e.preventDefault();
current = e.target;
dragging = true;
x = e.clientX;
y = e.clientY;
ox = current.offsetLeft;
oy = current.offsetTop;
window.onmousemove = function(e) {
if (dragging == true) {
var sx = e.clientX - x + ox,
sy = e.clientY - y + oy;
current.style.left = sx + "px";
current.style.top = sy + "px";
return false;
}
};
window.onmouseup = function(e) {
dragging && (dragging = false);
};
};
};
var el = $('.drag_wp');
for(var i = 0; i < el.length; i++){
enableDragging(el[i]);
};
html&amp; CSS
<div class="drag_wp">
<img src="..." class="drag_el">
<div></div>
....// other div
</div>
.drag_wp{
position: absolute;
width: auto;
height: auto;
background:red;
}
.drag_el{
position: absolute;
width: 200px;
height: auto;
}
答案 0 :(得分:1)
function enableDraggin(el){
var dragging = dragging || false, x, y, ox, oy, current;
el.onmousedown = function(e){
e.preventDefault();
current = e.target;
//just add this
if(!$(current).hasClass(".drag_wp"))
current = $(current).closest(".drag_wp")[0];
//just add this
dragging = true;
x = e.clientX;
y = e.clientY;
ox = current.offsetLeft;
oy = current.offsetTop;
window.onmousemove = function(e) {
if (dragging == true) {
var sx = e.clientX - x + ox,
sy = e.clientY - y + oy;
current.style.left = sx + "px";
current.style.top = sy + "px";
return false;
}
};
window.onmouseup = function(e) {
dragging && (dragging = false);
};
};
};
e.target
返回被点击的元素(大多数情况下是HTML的图片)。如果它没有类.drag_wp
,只需找到与该类最近的父级并将其用作当前级。
此外,由于您已经在使用jquery,您可能会发现使用jQuery UI中的相应插件会更好:http://jqueryui.com/draggable/
答案 1 :(得分:1)
我对您的代码进行了一些修改:
function enableDragging(el) {
var dragging = dragging || false,
x, y, ox, oy, current;
el.onmousedown = function (e) {
e.preventDefault();
current = e.target.parentNode; // <--- current should be wrapper, not image
dragging = true;
x = e.clientX;
y = e.clientY;
ox = current.offsetLeft;
oy = current.offsetTop;
window.onmousemove = function (e) {
if (dragging == true) {
var sx = e.clientX - x + ox,
sy = e.clientY - y + oy;
current.style.left = sx + "px";
current.style.top = sy + "px";
return false;
}
};
window.onmouseup = function (e) {
dragging && (dragging = false);
};
};
};