あなたのコメントに基づいて、いくつかの異なる解決策があります。
特別な色のボックスを一時的に既存のボックスに置き換えるか (現在の動作)、指定した n 番目の子ボックスの後にそれらを追加するか (コメントに基づいて) はわかりませんでした。
これらの両方で、removeSpecialBoxes
メソッドは最初に呼び出されますcheckWidth
置換方法 ( jsfiddle )
このアプローチは、削除したアイテムを追跡し、後でまったく同じアイテムを再挿入する必要があるため、少し複雑です。以下の JS に加えて、いくつかの CSS の変更もありました。つまり、特別なボックスに ID を持たせ、それぞれに class を持たせましたtest
。
まず、保管されたボックスを保持するための新しいオブジェクトを作成しました。
var theStored = {};
次に、特別なボックスの作成と削除を処理するメソッドをいくつか作成しました。
function makeSpecialBox(id, content) {
// Create a new special box with the class name and the content
var specialBox = $("<div />", {
"id": id,
"class": "test"
}).html(content);
// Return the special box
return specialBox;
}
function removeSpecialBoxes() {
// Get the special boxes
var specialBoxes = $("#wrapper div").filter(".test");
// For each special box
specialBoxes.each(function(index, specialBox) {
// Get the special box's ID
var specialBoxId = $(specialBox).attr("id");
// Get the associated stored box
var storedBox = theStored[specialBoxId];
// Replace the special box with the stored box
$(specialBox).replaceWith(storedBox);
});
}
次にsetNthPosition
、既存のボックスの保管と特別なボックスへの交換を処理するようにメソッドを変更しました。
function setNthPosition(theDiv, newPos){
// Generate a new special box
var specialBox = theDivs["div"+theDiv].clone();
// Get the special box ID
var specialBoxId = specialBox.attr("id");
// Get the existing box to replace
var existingBox = $("#wrapper div:nth-child("+newPos+")");
// Clone the existing box and store it based on the special box ID
theStored[specialBoxId] = existingBox.clone();
// Replace the existing box with the special box
existingBox.replaceWith(specialBox);
}
メソッドの追加 ( jsfiddle )
このアプローチは少し単純です。これは基本的に、いくつかのマイナーな変更を加えた、質問の既存のコードです。
function makeSpecialBox(className, content) {
// Create a new special box with the class name and the content
var specialBox = $("<div />").addClass(className).html(content);
// Return the special box
return specialBox;
}
function removeSpecialBoxes() {
// Get the special boxes
var specialBoxes = $("#wrapper div").filter("[class^='test']")
// Remove the special boxes
specialBoxes.remove();
}
function setNthPosition(theDiv,newPos){
// Generate the special box
var theClone=theDivs["div"+theDiv].clone();
// Append the special box after the nth-child
$("#wrapper div:nth-child("+newPos+")").after(theClone);
}