簡體   English   中英

為什么在html中兩次插入相同的圖像對象不起作用?

[英]Why inserting the same image object twice in html does not work?

我正在嘗試將同一張圖片插入兩個不同的div中。 但是圖像僅顯示在最后一個圖像中。 看起來同一對象只能在html中出現一次。

var img = new Image();
img.src = '/image1.jpg';
img.onload = function(){
   $('#div1').html(img);
   $('#div2').html(img);
}

僅#div2顯示圖像。

更新以添加代碼段

 var img = new Image(); img.src = "http://via.placeholder.com/350x150"; img.onload = function(){ img.id = '#jcrop-target'; $('#jcrop').html(img); img.id = '#jcrop-preview'; $('#preview').html(img); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="jcrop"></div> <div id="preview"><div> 

我使用了此解決方案,但它看起來非常優雅。

 var img = new Image(); img.src = 'http://via.placeholder.com/350x150'; img.onload = function(){ $('#jcrop').html('<img id="jcrop-target" src="'+img.src+'" />'); $('#preview').html('<img id="jcrop-preview" src="'+img.src+'" />'); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="jcrop"></div> <div id="preview"></div> 

Image()構造函數創建一個新的HTMLImageElement實例。 它的功能等效於document.createElement('img') 這將在DOM樹結構中創建一個具有其尺寸和屬性的節點。 它還在樹結構中具有特定位置。 它不能在樹結構中的兩個不同位置。 因此,如果需要,您將不得不制作另一個元素,或者可以嘗試克隆它。

如果需要將圖像放在多個div元素中,則可以使用class代替id。

var img = new Image();
img.src = '/image1.jpg';
img.onload = function(){
    $('.div').html(img);
}

這樣就可以在多個div添加相同的圖像

<div class="div" id="div1"></div>
<div class="div" id="div2"></div>

你去

 var elem1 = document.createElement("img"); elem1.setAttribute("src", "http://via.placeholder.com/350x150"); var elem2 = document.createElement("img"); elem2.setAttribute("src", "http://via.placeholder.com/350x150"); document.getElementById("div1").appendChild(elem1); document.getElementById("div2").appendChild(elem2); 
 <div id="div1"> </div> <div id="div2"> </div> 

http://via.placeholder.com/350x150替換為您的源/image1.jpg

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM