如何使用处理程序获得可拖动的图像?我读过处理程序应该位于可拖动的内部,但我实际上不能在图像中包含另一个元素。
我这里有一个 fiddle ,可以更好地演示:
http://jsfiddle.net/index/bfpWv/10/
问题是我应该如何在#viewport
内拖动并仍然移动#image
?
编辑
我认为这个问题有点模糊:
因为现在(在 fiddle 上)当您首先单击#image
并拖动时,它会拖动#image
。但是当您首先单击#viewport
时,却没有。这就是我想要发生的事情,当您首先单击 #viewport
并拖动时,它仍然会拖动 #image
。
最佳答案
看来jquerydraggable需要将处理程序放在draggable中。您只需几行代码即可编写自己的可拖动对象。查看我的演示 here
HTML:
<div id="container">
<img id="image" src="http://thechive.files.wordpress.com/2011/03/hot-sexy-redheads-12.jpg" />
<div id="viewport"></div>
</div>
JS:
$(document).ready(function(){
var isDragging,
top = 0, left = 0,
curX, curY;
$("#image").mousedown(function (e) {
e.preventDefault();
});
$("#container").mousedown(function (e) {
isDragging = true;
curX = e.pageX;
curY = e.pageY;
left = Number($("#image").css("margin-left").
toString().replace("px", ""));
top = Number($("#image").css("margin-top").
toString().replace("px", ""));
});
$(document).mouseup(function () {
if (isDragging){
// reset
isDragging = false;
top = 0;
left = 0;
}
});
$("#container").mousemove(function(e){
if (!isDragging) {
return;
}
left += e.pageX - curX;
top += e.pageY - curY;
// set the position
$("#image").css("margin-left", left + "px").
css("margin-top", top + "px");
curX = e.pageX;
curY = e.pageY;
});
});
关于javascript - jqueryui 可拖动移动图像与处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14887839/