如何使用 jquery 将可拖动项目返回到其初始位置
我有一组图像放置为 position:relative
(一个挨着另一个显示)。
我使用此代码来拖放它们(从 jQuery API 文档中窃取,根据我的需要进行修改)。
$(function() {
$( ".draggable" ).draggable({
start: function(event, ui) {
// Show start dragged position of image.
var Startpos = $(this).offset();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
pos_left = Startpos.left; //pos_left is global
pos_top = Startpos.top; //pos_top is also global
},
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).offset();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
$(this).css('position', "fixed"); //tried absolute and relative, too
$(this).css('left', pos_left);
$(this).css('top', pos_top);
}
});
$( ".droppable" ).droppable({
drop: function( event, ui ) {
id = $(this).attr('id');
alert(id);
}
});
});
我想做的是在用户放置可拖动元素后将其返回到其初始位置。然而,因为我的元素相对定位在初始左侧,所以所有元素的顶部坐标都是相同的(或者这是我从文档中理解的——我在这里可能是错的)。因此,虽然图像返回,但它们实际上将每个图像堆叠在另一个之上。
我做错了什么?我该怎么办?
I have a set of images placed as position:relative
(showing one next to the other).
I use this code to drag and drop them (stolen from the jQuery API documentation, modified to my needs).
$(function() {
$( ".draggable" ).draggable({
start: function(event, ui) {
// Show start dragged position of image.
var Startpos = $(this).offset();
$("div#start").text("START: \nLeft: "+ Startpos.left + "\nTop: " + Startpos.top);
pos_left = Startpos.left; //pos_left is global
pos_top = Startpos.top; //pos_top is also global
},
stop: function(event, ui) {
// Show dropped position.
var Stoppos = $(this).offset();
$("div#stop").text("STOP: \nLeft: "+ Stoppos.left + "\nTop: " + Stoppos.top);
$(this).css('position', "fixed"); //tried absolute and relative, too
$(this).css('left', pos_left);
$(this).css('top', pos_top);
}
});
$( ".droppable" ).droppable({
drop: function( event, ui ) {
id = $(this).attr('id');
alert(id);
}
});
});
What I am trying to do is to return the draggable element to its initial position, after user drops it. However because my elements are relatively positioned the initial left,top coords are the same for all of them (or this is what I understand from the documentation -- I might be wrong here). So although images return, they actually stack each one on top of the other.
What am I doing wrong? What am I supposed to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
出色地。不要自己执行此操作,而是使用可拖动的恢复选项。从 jQuery UI 码头:
Well. Instead of doing that by yourself use the revert option of the draggable. From the jQuery UI docks:
您可以将其位置设置为相对位置,top=0px,left=0px。用这段代码为我工作:
You could make its position relative, top=0px, and left=0px. Worked for me with this code: