[英]How to clone the contents of a div into another div with JavaScript?
我想將div leftSide
的圖像克隆到div rightSide
。 每次單擊主體時,應將左側div上的圖像克隆到右側div中。 但是我用我做的代碼無法得到結果。 我的代碼有什么錯誤嗎? 我想使用JavaScript。
這是我的代碼:
var theLeftSide = document.getElementById("leftSide");
var width = 500; var height = 500;
top_position = 0; var left_position = 0,
var numberOfFaces = 5;
var theRightSide = document.getElementById("rightSide");
var leftSideImages = theLeftSide.cloneNode(true);
document.getElementById("rightSide").appendChild(leftSideImages);
for (var i = 0; i < 5; i++) {
createElement(i);
numberOfFaces += 5;
function createElement() {
var image = document.createElement('img');
image.src = "smile.png";
image.style.position = 'absolute';
image.style.top = top_position + "px";
image.style.left = left_position + "px";
theLeftSide.appendChild(image);
top_position = Math.random() * 500 ;
left_position = Math.random() * 500 ;
這是一個在原始javascript中克隆HTMLElement
的簡單示例:
其他信息可以在MDN中找到
function CloneCtrl() { 'use strict'; var self = this; self.source = document.querySelector('.source'); self.target = document.querySelector('.target'); self.cloneSource = function(event) { var clone = self.source.cloneNode(true); self.target.appendChild(clone); } document .getElementById('cloneBtn') .addEventListener('click', self.cloneSource) ; } document.addEventListener('DOMContentLoaded', CloneCtrl);
.source { background: lightseagreen; width: 100px; height: 100px; line-height: 100px; overflow: hidden; margin: 5px; display: inline-block; text-align: center; color: #fff; } .target { border: 1px solid lightcoral; min-height: 110px; }
<div><button id="cloneBtn">Clone Source</button></div> <div class="source">SOURCE</div> <hr> <div class="target"></div>
使用jQuery,您可以做到這一點:
$('#div2').html($('#div1').html());
從以下問題中發現: 將一個div的內容復制到另一個div中 。
您實際上並未提供很多詳細信息,因此我可以提供最好的信息,希望對您有所幫助!!
如果您在頁面上有第二個div,則可以嘗試一下。
document.getElementById("SecondDv").innerHTML = document.getElementById("FirstDv").innerHTML;
這會將FirstDiv中的所有內容復制到Second。 lmk(如果有效)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.