脚本的目标是拖动元素,但保留元素的副本。
function makeDraggable() {
$('.col-md-4').addClass('is-draggable');
$('.is-draggable').draggable({
start: function(event, ui){
if($(this).hasClass('not-draggable'))
return;
var cl = $(this).clone();
$(this).after(cl);
var of = cl.offset();
$(this).addClass('rect').offset({top:of.top,left:of.left}).css({width:cl.css('width'), height:cl.css('height')});
makeDraggable();
$(this).addClass('not-draggable');
}
});
}
makeDraggable();
当你在某些盒子上躲开时,它会克隆盒子,然后可拖动将这个元素放在左上角,并且不允许设置我自己的偏移量。我希望可拖动元素留在同一个地方,不要跳。演示jsfidle
答案 0 :(得分:2)
您无法使用偏移量,因为它已被拖动事件使用。您可以使用边距来抵消可拖动的。
另外,使用ui.helper获取偏移量
var of = $(ui.helper).offset();
$(this).addClass('rect').css({'margin-top':of.top,'margin-left':of.left}).css({width:cl.css('width'), height:cl.css('height')});
外部JSFiddle:http://jsfiddle.net/9QmbG/22
function makeDraggable() {
$('.col-md-4').addClass('is-draggable');
$('.is-draggable').draggable({
start: function (event, ui) {
var $this = $(this);
if ($this.hasClass('not-draggable')) return;
var cl = $this.clone();
$this.after(cl);
var of = $(ui.helper).offset();
$this.addClass('rect').css({
'margin-top': of.top,
'margin-left': of.left
}).css({
width: cl.css('width'),
height: cl.css('height')
});
makeDraggable();
$this.addClass('not-draggable');
}
});
}
makeDraggable();
#score {
height:50px;
}
.col-md-4 {
width:40px;
height:40px;
margin:10px 20px;
border:1px solid #000000;
float:left;
cursor:pointer;
text-align:center;
line-height:40px;
position:relative;
top:0;
left:0;
}
.rect {
position: absolute;
z-index:100000;
border-style: dashed;
border-width: 2px;
}
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<div id="score"> </div>
<div class="col-md-4">1</div>
<div class="col-md-4">2</div>
<div class="col-md-4">3</div>