一次选择一个图像

时间:2016-03-01 15:02:15

标签: javascript css

这是代码:

function select(element){
   element.onclick = function(){
      element.classList.toggle('selected');
  }
}
Array.from(document.getElementsByClassName('my_class_img')).forEach(select);

这是css:

.selected{
border: 3px solid blue;
box-sizing: border-box;
}

图像具有与my_class_img相同的类,如何在时间选择一个img(现在我可以选择多个img)?谢谢大家!

编辑:使用代码@epascarello给了我,我的其他功能(myfun(i))不再起作用了:

        var src1 = "";
        var img = new Array();
        img[0] = new Image();
        img[0].src = "../images/poggiatesta2.jpg";
        img[1] = new Image();
        img[1].src = "../images/poggiatesta1.JPG";
        img[2] = new Image();
        img[2].src = "../images/poggiatesta3.jpg";
            for (var i = 0; i < img.length; i++) {
            var imagetag = document.createElement("img");
            var onclick = document.createAttribute("onclick");
            onclick.value = "myfun(" + i + ")";

            var sorc = document.createAttribute("src");
            sorc.value = img[i].src;

            var id = document.createAttribute("id");
            id.value = "my_image" + i;

            var clas = document.createAttribute("class");
            clas.value = "my_image_clas";

            imagetag.setAttributeNode(clas);
            imagetag.setAttributeNode(onclick);
            imagetag.setAttributeNode(sorc);
            imagetag.setAttributeNode(id);
            document.body.appendChild(imagetag);
            }
            function myfun(i) {

                src1 = document.getElementById('my_image' + i).src;

            }

2 个答案:

答案 0 :(得分:2)

跟踪最后选择的内容或循环遍历所有元素并删除所选的类。

var _last = null;
function select(element){
   element.onclick = function(){
      element.classList.toggle('selected');
      if(_last) _last.classList.remove("selected");
      _last = element.classList.contains("selected") ? element : null;
  }
}

或使用单选按钮:)

答案 1 :(得分:2)

我会这样做并跳过使用脚本。

&#13;
&#13;
input {
  display: none
}

input:checked ~ img {
  border: 3px solid blue;
  box-sizing: border-box;
}
&#13;
<label>
  <input type='radio' name='sel_img'>
  <img src='http://placehold.it/100/100'>
</label>
<label>
  <input type='radio' name='sel_img'>
  <img src='http://placehold.it/100/100'>
</label>
<label>
  <input type='radio' name='sel_img'>
  <img src='http://placehold.it/100/100'>
</label>
<label>
  <input type='radio' name='sel_img'>
  <img src='http://placehold.it/100/100'>
</label>
&#13;
&#13;
&#13;