简体   繁体   中英

change image border color onclick

I have a page where the users needs to pick a color for a tshirt.

When the user selects a color, I want the image's border color to change to green.

And if the user click a different color, it needs to put back the default border color and change the border color of the new image that was clicked.

Here is exactly what I am trying to do.

Any idea how I could do that ?

Say your image is displayed using img tag as below:

  <img name="img01" id="img01" src="image.gif" border="2" bordercolor="#000000">

implement onClick fnction fnChangeBorder as below

   function fnChangeBorder(){
      document.getElementById("img01").style.borderColor="#00FF00";
   }

or

   function fnChangeBorder(){
      var imgElement = document.getElementById("img01");
      imgElement.setAttribute("style:borderColor", "#00FF00");
   }

or you can define a style class and do like:

   function fnChangeBorder(){
      document.getElementById("img01").style.className="greenClass";
   }

EDIT:

For multiple images, with indexed id, we can pass the index in the onclick function as:

  <img name="img1" id="img1" src="image.gif" border="2" bordercolor="#000000"
        onclick="javascript:fnChangeBorder(1);">

  <img name="img2" id="img2" src="image.gif" border="2" bordercolor="#000000"
        onclick="javascript:fnChangeBorder(2);">

And update fnChangeBorder as:

   function fnChangeBorder(index){
      document.getElementById("img"+index).style.className="greenClass";
   }

For multiple images, with non-indexed id, we can pass the id in the onclick function as:

  <img name="imgabc" id="imgabc" src="image.gif" border="2" bordercolor="#000000"
        onclick="javascript:fnChangeBorder('imgabc`);">

  <img name="imgxyz" id="imgxyz" src="image.gif" border="2" bordercolor="#000000"
        onclick="javascript:fnChangeBorder('imgxyz');">

And update fnChangeBorder as:

   function fnChangeBorder(imageId){
      document.getElementById(imageId).style.className="greenClass";
   }

Create one class with your styles. For example

.selected{
   border : 1px solid green;
}

Then apply the className on click of the item. Avoid using setAttribute to set Class name of a item. It is having some issues. Then onclick of the image remove the selected class name on all items and then apply class name selected to the target image.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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