繁体   English   中英

当使用 Javascript 单击图像 A 时,如何将图像 B 的 src 更改为图像 A 的 src?

[英]How do I change image B's src to Image A's src when Image A is clicked with Javascript?

目标:单击图像 A 时,页面底部会出现相同的图像。 需要为多个图像工作。

当单击图像 A 时,我需要图像 B 现在与图像 A 具有相同的 src。或者生成单击图像的副本。 这也应该能够适用于多张图片。

例如,如果我单击屏幕上的 5 个图像(图像 A-01、A-02、A-03、A-04、A-05)....

在页面底部应该有这 5 张图片

我试过 HTML:

<img id="myImage" src="http://placehold.it/150">
<img id="new" src="http://placehold.it/200">

JS

$(function(){
  $("#myImage").click(function() {
    $("#new").attr("src","http://placehold.it/150")
    });
});

它可以替换一张图片,但我需要相同的代码来处理多次图片点击。

另一个带有事件侦听器的提议。

 var imgCount = 5, i; for (i = 1; i <= 5; i++) { document.getElementById('img' + i).addEventListener('click', setImg('img' + i), false); } function setImg(id) { return function () { var img = document.createElement('img'); if (imgCount) { imgCount--; img.src = document.getElementById(id).src; document.getElementById('footer').appendChild(img); }; } }
 <img id="img1" src="http://lorempixel.com/200/100/city/1" /> <img id="img2" src="http://lorempixel.com/200/100/city/2" /> <img id="img3" src="http://lorempixel.com/200/100/city/3" /> <img id="img4" src="http://lorempixel.com/200/100/city/4" /> <img id="img5" src="http://lorempixel.com/200/100/city/5" /> <div id="footer"></div>

这将帮助你

 function changeSrc(id){ document.getElementById('footer').src = document.getElementById(id).src; }
 <img src="http://imgsv.imaging.nikon.com/lineup/lens/zoom/normalzoom/af-s_dx_18-140mmf_35-56g_ed_vr/img/sample/sample1_l.jpg" height="200" width="auto" id="img1" onclick="changeSrc(this.id)"/> <img src="https://images-eu.ssl-images-amazon.com/images/G/02/uk-electronics/product_content/Nikon/ECS-NK1308141-B00ECGX8FM-2L-1024w683q85s10-BKEH_London_Paris__0316.jpg" height="200" width="auto" id="img2" class="image" onclick="changeSrc(this.id)"/> <img src="" height="200" width="auto" id="footer" class="image" />

尝试这个:

<img src="https://randomuser.me/api/portraits/thumb/men/57.jpg" class="a">
<img src="https://randomuser.me/api/portraits/thumb/women/14.jpg" class="a">
<img src="https://randomuser.me/api/portraits/thumb/women/7.jpg" class="a">
<br>
<div id="sectionB">
  <img src="http://placehold.it/48" class="b">
  <img src="http://placehold.it/48" class="b">
  <img src="http://placehold.it/48" class="b">
</div>
<br>
<button id="reset">Reset</button>

===

$(function() {
  $('.a').click(function() {
    var img = $(this).attr('src');
    var index = $(this).index();

    $('.b').eq(index).attr('src', img);
  })

  $('#reset').click(function(){
    $('.b').attr('src', 'http://placehold.it/48');
  })
})

演示: https : //jsfiddle.net/j359yfor/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM