簡體   English   中英

javascript - 如何在不重新加載圖像的情況下將 img 標簽移動到 div 中?

[英]javascript - How to move an img tag into a div without reloading the image?

const div = document.createElement('div');
const span = document.createElement('span');
const img = document.querySelector('img');
const imgCloned = img.cloneNode();
div.appendChild(imgCloned);
div.append(span);
img.replaceWith(div);

它正在工作,並且正在將img移動到div元素中,但是,因為它是一個克隆圖像,所以還有另一個獲取圖像的請求。 如何在不重新加載圖像的情況下將img移動到div中?

只需其移動到創建的 div...

這個小小的stackblitz 項目有一個 function 來移動圖像,fork 它來玩代碼。

 const div = document.createElement('div'); const span = document.createElement('span'); div.append(document.querySelector('img')); div.append(span); document.body.insertBefore(div, document.body.firstChild); document.querySelector(`pre`).textContent = document.body.querySelector(`div`).outerHTML;
 <img src="https://picsum.photos/200/300"> <h3>Your html after move</h3> <pre></pre>

重新排序你正在做的事情

替換圖像,然后將圖像添加到 div 的開頭

 const div = document.createElement('div'); const span = document.createElement('span'); const img = document.querySelector('img'); div.append(span); img.replaceWith(div); div.insertAdjacentElement('afterbegin', img);
 <div> The image is here <img src="https://placekitten.com/200/300"> <span> other things live here </span> </div>

暫無
暫無

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

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