简体   繁体   English

jQuery追加错误的位置

[英]jQuery append wrong position

I'm trying to order elements from one list into two lists. 我正在尝试将元素从一个列表排序为两个列表。 However, when I drop the element and append it to the target div, the position is very strange (almost random). 但是,当我放下元素并将其附加到目标div时,位置非常奇怪(几乎是随机的)。

<div class='container'>// contains generated words, draggable
  <div class='word'>Word</div>
  <div class='word'>Word 2</div>
  ...
</div> 
<div class='target' id='target1'></div> // made droppable
<div class='target' id='target2'></div> // made droppable

The drop function: 放置功能:

$('.target').droppable({drop: function(e,ui) {
  $(this).append(ui.draggable);
}});

The following fiddle shows the problem with one target. 以下小提琴显示了一个目标的问题。

http://jsfiddle.net/YZ8vJ/12/ http://jsfiddle.net/YZ8vJ/12/

I'm clueless why this is happening, and I haven't found an answer on SO or on the internet... 我不知道为什么会这样,而且在SO或互联网上都找不到答案...

I think the position elements are append depends on the position you drop them. 我认为position元素的追加取决于您放置它们的位置。 I add a div in your html <div id="dropEleme"></div> so the drop elements append there. 我在您的html <div id="dropEleme"></div>添加了一个div,因此drop元素将附加在其中。 Also i change a bit your js code to reset style: 我也更改了您的js代码以重置样式:

js JS

var a = ["word", "word2", "word3"];
for (var i = 0; i < a.length; i++) {
    $('.words').append(makeDiv(a[i]));
}
function makeDiv(e) {
    return "<div class='word'>" + e + "</div>";
}
$('.word').draggable({revert:'invalid'});
$('.target').droppable({drop:function(e,ui) {
    $(ui.draggable).attr("style",""); //added this line to reset style, like position.
    $("#dropEleme").append(ui.draggable);
}});

fiddle 小提琴

using 运用

$(this).append(ui);

instead of 代替

$(this).append(ui.draggable);

fixes the problem..here's the fiddle: fiddle 解决问题..这是小提琴: 小提琴

Use this css class for .word : 将此CSS类用于.word

.word {
    background-color: coral;
    position:absolute;
    margin: 10px;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM