gpt4 book ai didi

javascript - 为什么在 html 中两次插入相同的图像对象不起作用?

转载 作者:太空宇宙 更新时间:2023-11-04 15:56:34 25 4
gpt4 key购买 nike

我正在尝试将相同的图像插入到两个不同的 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 树结构中创建一个节点及其维度和属性。它在树结构中也有特定的位置。它不能在树结构中的两个不同位置。因此,如果需要,您将不得不制作另一个元素,或者您可以尝试克隆它。

关于javascript - 为什么在 html 中两次插入相同的图像对象不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45261807/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com