我在一个容器中有 5 个图像,我必须将它们放入另一个容器中才能完成图像。将图像放入另一个容器后,我想根据图像的 ID 向该图像添加不同的类。这样这个图像片段就会粘在这个容器中存在的前一个图像上。
我能够实现拖放事件并在拖放事件后为每个图像添加一个类。我需要在我的代码中进行哪些更改才能根据其 ID 向每个图像添加不同的类
我的代码
<style>
.add-style {
position:absolute;
}
.north-style {
width: 375px;top: 10px;left: 11px;
}
.south-style {
width: 375px;top: 158px;left: 11px;
}
.east-style {
width: 163px;top: 10px;left: 223px;height: 250px;
}
.west-style {
width: 163px;top: 9px;left: 11px;height: 249px;
}
.center-style {
width: 126px;top: 71px;left: 135px;
}
</style>
<script>
$(function() {
$( "#sortable1" ).sortable({
connectWith: "div"
});
$( "#sortable2" ).sortable({
connectWith: "div",
stop: function( event, ui ) {
ui.item.addClass( "add-style" )
}
});
$( "#sortable1, #sortable2" ).disableSelection();
});
</script>
代码主体
<body>
<div class="row-fluid" >
<div class="span4">
<div class="span1"></div>
<div id="sortable1" class="well sidebar-nav sidebar-nav-fixed span11">
<legend>Collect Coupon parts</legend>
<span>1st part</span>
<img id="north-img" class="ui-state-highlight" src="images/demo/north.png" >
<span>2nd part</span>
<img id="south-img" class="ui-state-highlight" src="images/demo/south.png" >
<span>3rd part</span>
<img id="east-img" class="ui-state-highlight" src="images/demo/east.png" >
<span">4th part</span>
<img id="west-img" class="ui-state-highlight" src="images/demo/west.png" >
<span>5th part</span>
<img id="center-img" class="ui-state-highlight" src="images/demo/center.png">
</div>
</div>
<div id="sortable2" class=" well sidebar-nav sidebar-nav-fixed span8">
<legend>Canvas section</legend>
</div>
</div>
</body>
最佳答案
首先将您的类(class)更改为以下内容。
显示了两个示例,其他 3 个也更改。
.north-img-style {
width: 375px;top: 10px;left: 11px;
}
.south-img-style {
width: 375px;top: 158px;left: 11px;
}
然后在这部分代码中添加这两行
stop: function( event, ui ) {
var theID = ui.item.attr('id');
ui.item.addClass(theID + '-style');
}
var theID
获取元素的 id
,然后我们只需添加具有相同 ID 的 Class,但为其添加 -style。所以这将适用于所有五个不同的类(class)。
编辑
是的,您一次可以添加多个类(class)。像这样用逗号分隔:
var theID = ui.item.attr('id');
ui.item.addClass(theID + '-style', 'add-style');
关于javascript - 在放置事件后为每个具有不同 id 的图像添加不同的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21276632/