javascript - 在javascript中单击图像后更改图像(不使用下拉菜单)

标签 javascript jquery arrays html

现在我正在通过下拉选择更改图像。但我想通过单击图像选择来更改图像,例如。
enter image description here

如果用户点击绿色T恤图像,则在 <div> 中设置绿色图像,如果用户点击黄色T恤,则将黄色T恤设置为<div>. 但现在我正在使用下拉菜单来执行此过程。

var bgArray = [
  'https://d3s16h6oq3j5fb.cloudfront.net/1.13.0/img/new-city-home/bang-img/softtoys3.jpg',
  'https://d2z4fd79oscvvx.cloudfront.net/0020715_be_my_valentine_chocolate_box_205.jpeg'
]
$('#imageroom').on('change', function() {
  value = $(this).val() - 1;
  $('#backgroundIMage').css({
    'background-image': 'url(' + bgArray[value] + ')'
  });
});
#backgroundIMage {
  width: 400px;
  height: 300px;
  outline: 1px dotted gray;
  margin: 0 auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<label>Change image</label>
<select size="1" id="imageroom">
  <option value="1">Image 1</option>
  <option value="2">IMage 2</option>
</select>


<!-- for demo only -->
<hr>
<div id="backgroundIMage"></div>

最佳答案

您可以处理图像上的click 事件。在下面的示例中,我循环访问 bgArray 并动态显示该数组中的所有图像。

当单击其中一张图像时,我会在 backgroundIMage 元素中显示该图像。请注意,我正在使用 event delegation确保图像点击适用于动态添加到选择器的任何图像。

var bgArray = [
  'https://d3s16h6oq3j5fb.cloudfront.net/1.13.0/img/new-city-home/bang-img/softtoys3.jpg',
  'https://d2z4fd79oscvvx.cloudfront.net/0020715_be_my_valentine_chocolate_box_205.jpeg'
];

$("#picker").on("click", "img", function() {
  //use event delegation to handle click event of any img tags in #picker
  $('#backgroundIMage').css({
    'background-image': 'url(' + this.src + ')'
  });
  
  //toggle selected
  $("#picker img").removeClass("selected");
  $(this).addClass("selected");
});

$(function() {
  //initialize the picker on document load
  bgArray.forEach(function(src) {
    var img = new Image(50, 50);
    img.src = src;
    $("#picker").append(img);
  });
  
  //default the first one to be selected
  $("#picker img").first().trigger("click");
});
#backgroundIMage {
  width: 400px;
  height: 300px;
  outline: 1px dotted gray;
  margin: 0 auto;
}

#picker img {
  padding: 5px;
}

.selected {
  background-color: dodgerblue;
  border-radius: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
Change image
<div id="picker"></div>

<hr>
<div id="backgroundIMage"></div>

关于javascript - 在javascript中单击图像后更改图像(不使用下拉菜单),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35738654/

相关文章:

javascript - 使用 API 分页

Javascript - 将类添加到数组中的元素

jquery - 使用 CSS 使图像正确定位/分层

c - 局部指针数组问题

c++ - 如何交换数组中 Min 和 Max 的位置?

javascript - 我可以根据点击 li className 在一个 php 页面中显示单独的数据表吗?

javascript - sequelize 中的引用字段是什么?

javascript - jQuery:使 div 可点击以检查嵌套的复选框

jquery - 使用 jQuery 对图像进行分类

python - 在 Python 中查找数组中满足 inf < element < sep 的元素