如果要恢复到某个位置,我正在尝试更改我的拖动颜色。在此示例中,当您将红色框拖到右侧的绿色框时,红色框会变为蓝色。我把它设置好,当你把一个盒子拖到另一个盒子的顶部时,它会恢复到它的位置。但是如果盒子正在恢复到左边的容器,我希望它变回红色,如果你在那里手动拖动它就会这样做。我也可以这样做,如果一个盒子在左侧容器中它总是红色,但我不知道该怎么做。任何帮助是极大的赞赏。提前谢谢。
这是HTML:
<div id="box">
<div class="peg"> </div>
<div class="space"> </div>
<div class="peg"> </div>
</div>
<div id="game">
<ul class="row">
<li class="hole"> </li>
<li class="hole"> </li>
</ul>
</div>
CSS:
#game {
position: absolute;
top: 15px;
left: 135px;
background: wheat;
padding: 15px;
padding-bottom: 0;
}
.row {
position: relative;
margin-left: auto;
margin-right: auto;
height: 75px;
margin-bottom: 15px;
background-color: olive;
}
.hole {
width: 75px;
height: 75px;
float: left;
background-color: aqua;
opacity: 0.3;
margin-left: 6px;
}
#box {
position: absolute;
left: 15px;
top: 15px;
width: 90px;
padding-bottom: 15px;
background-color: wheat;
padding-top: 15px;
padding-left: 15px;
}
.peg {
width: 75px;
height: 75px;
background-color: red;
z-index: 1;
}
.space {
height: 15px;
width: 75px;
}
.top {
background-color: blue;
width: 75px;
height: 75px;
z-index: 1;
}
使用Javascript:
$('.peg' ).draggable({
snap: ".hole",
snapMode: "inner",
snapTolerance: 40,
//scope: "zappa",
//revert: 'invalid',
stop: function(){
$(this).draggable('option','revert','invalid');
},
//helper: "clone"
});
$('.peg').droppable({
tolerance: 'fit'
});
$('.peg').droppable({
greedy: true,
tolerance: 'touch',
drop: function(event,ui){
ui.draggable.draggable('option','revert',true);
}
});
$('.hole').droppable({
drop: function(e,ui) {
$(ui.draggable).removeClass('peg').addClass('top');
},
//scope: "zappa"
});
$('#box').droppable({
drop: function(e,ui) {
$(ui.draggable).removeClass('top').addClass('peg');
},
//scope: "zappa"
});
答案 0 :(得分:2)
相反,您可以为$('.hole').droppable(...)
创建一个控件类,以便在盒子已经在孔中时实际阻止其他盒子发生变化。
$('.hole').droppable({
drop: function(e,ui) {
//Check the hole control class
if(!$(this).hasClass('full')){
//its empty so change the class of the box
$(ui.draggable).removeClass('peg').addClass('top');
//if you want to prevent the box in the hole from being draggable again uncomment next line
//$(ui.draggable).unbind('mousedown');
//put the hole control class
$(this).addClass('full')
}else{
//its full
}
},
out: function(){
//if the item can go out of the hole then
//remove the hole control class
$(this).removeClass('full')
}
});
<强>更新强>
如果你需要控制当一个盒子出洞时会发生什么,那么将out
函数添加到droppable,我更新了链接和代码。
答案 1 :(得分:0)
我们也可以解决以下问题:
jQuery的替代方式:
$('.peg').draggable({
snap: ".hole",
snapMode: "inner",
snapTolerance: 40,
stop: function() {
$(this).draggable('option', 'revert', 'invalid');
}
});
$('.peg').droppable({
tolerance: 'fit',
greedy: true,
tolerance: 'touch',
drop: function(event, ui) {
ui.draggable.draggable('option', 'revert', true);
}
});
$('.hole').droppable({
drop: function(e, ui) {
$(ui.draggable).switchClass('peg', 'top');
},
});
$('#box').droppable({
drop: function(e, ui) {
$(ui.draggable).switchClass('top', 'peg');
},
});
您可以在代码栏上找到完整的解决方案,因此请点击http://codebins.com/codes/home/4ldqpbs