我试图在我的应用程序中实现一个选择多个元素的功能,但由于我是前端开发的新手,我在控制JavaScript的事件时遇到了一些麻烦。 CSS。我找到了this post,所以我使用它作为我的向导。
在使用Selectable()函数之前,我添加了一个类(带有一些CSS),为我的元素提供了选中它的外观(一次点击一个),如果我想取消它,我只需点击画布(触发一个删除类的功能" selectedEffect")。
但是现在我想选择多个元素(将来我希望能够对它们进行分组),所以我开始使用Selectable(),正如我所说,我发现了帖子,这对我有所帮助。我能够将这段代码复制到我的项目中:
// this creates the selected variable
// we are going to store the selected objects in here
var selected = $([]), offset = {top:0, left:0};
$( "#canvas > div" ).draggable({
start: function(ev, ui) {
editorContent.addClass("hidden");
if ($(this).hasClass("ui-selected")){
selected = $(".ui-selected").each(function() {
var el = $(this);
el.data("offset", el.offset());
});
}
else {
selected = $([]);
$("#canvas > div").removeClass("ui-selected");
}
offset = $(this).offset();
},
drag: function(ev, ui) {
$(currentElement).removeClass("selectedEffect");
$(currentArrow).removeClass("selectedArrow");
var dt = ui.style.top - offset.top, dl = ui.style.left - offset.left;
// take all the elements that are selected expect $("this"), which is the element being dragged and loop through each.
selected.not(this).each(function() {
// create the variable for we don't need to keep calling $("this")
// el = current element we are on
// off = what position was this element at when it was selected, before drag
var el = $(this), off = el.data("offset");
el.css({top: off.top + dt, left: off.left + dl});
});
}
});
$( "#canvas" ).selectable();
// manually trigger the "select" of clicked elements
$( "#canvas > div" ).click( function(e){
if (e.metaKey == false) {
// if command key is pressed don't deselect existing elements
$( "#canvas > div" ).removeClass("ui-selected");
$(this).addClass("ui-selecting");
}
else {
if ($(this).hasClass("ui-selected")) {
// remove selected class from element if already selected
$(this).removeClass("ui-selected");
}
else {
// add selecting class if not
$(this).addClass("ui-selecting");
}
}
$( "#canvas" ).data("canvas")._mouseStop(null);
});
但是,在实现此功能后,我仍然有一些错误:
答案 0 :(得分:1)
我只是想出来了。问题是,因为我在动画中添加动态元素,所以我必须在创建的地方将以下函数绑定到我的可拖动元素:
$( "#myNewlyCreatedElement" ).draggable({
start: function (event, ui) {
if ($this.hasClass("ui-selected")) {
// if this is selected, attach current offset
// of each selected element to that element
selected = $(".ui-selected").each(function() {
var el = $(this);
el.data("offset", el.offset());
});
} else {
// if this is not selected, clear current selection
selected = $([]);
$( "#canvas > div" ).removeClass("ui-selected");
}
offset = $this.offset();
},
drag: function (event, ui) {
// drag all selected elements simultaneously
var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;
selected.not(this).each(function() {
var $this = $(this);
var elOffset = $this.data("offset");
$this.css({top: elOffset.top + dt, left: elOffset.left + dl});
});
}
});