我有两个功能,他们做的是他们复制按钮的点击div,它工作正常,但我想当我克隆div,我点击按钮改变克隆div下面的位置,因为它留在它的地方,我该怎么办?这是我的代码:
document.getElementById('CloneBtn').onclick = duplicate;
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "duplicetor" + ++i;
original.parentNode.appendChild(clone);
}
<div id="duplicater">
<p>Clone me</p>
</div>
<button type="button" id="CloneBtn" onlick="duplicate()">Clone Div</button>
答案 0 :(得分:2)
将#duplicater
元素包装在另一个容器中,并将按钮分开。新元素将成为新克隆的parentNode
并保持整齐有序。
document.getElementById('CloneBtn').onclick = duplicate;
var i = 0;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "duplicetor" + ++i;
original.parentNode.appendChild(clone);
}
<div>
<div id="duplicater">
<p>Clone me</p>
</div>
</div>
<button type="button" id="CloneBtn" onlick="duplicate()">Clone 1</button>
更新:根据您的评论添加标题。
document.getElementById('CloneBtn').onclick = duplicate;
var i = 1;
var original = document.getElementById('duplicater');
function duplicate() {
var clone = original.cloneNode(true);
clone.id = "duplicetor" + ++i;
original.parentNode.appendChild(clone);
clone.insertAdjacentHTML('beforebegin', '<h3>Cloned</h3>');
}
<div>
<div id="duplicater">
<p>Clone me</p>
</div>
</div>
<button type="button" id="CloneBtn" onlick="duplicate()">Clone 1</button>