简体   繁体   中英

how to do this with javascript? it's like a toggle but I don't seem to find toggle function

I'm trying to do this with javascript instead of jquery. I want to click on a picture then the picture will have borders but if I click on it again then the border will be gone. don't have much idea how it's done anyone can give me a hand?

allImages = document.getElementsByTagName("img");

    for(i=0;i<allImages.length;i++)
{
    allImages[i].onclick=function()
    {
    this.style.borderColor="red";
    this.style.borderStyle="solid";
    }
}

for toggle a image with id try this code

var img = document.getElementById('image-id');

if( ! img.hasBorder ) {

     img.style.border="2px solid #f00";
     img.hasBorder = true;

} else {

     img.style.border = "";
     img.hasBorder = false;

}

Updated code

allImages = document.getElementsByTagName("img");

for(i=0; i< allImages.length; i++ )
{
    allImages[i].onclick = function( e )
    {
           this.style.border = ( this.style.border == '')? "2px solid red":'';
    }
}

What you can do is create two classes one having border and second having border none.

Now when event fire check if first class is applly then remove it and apply second class.

Example

var test = document.getElementById("test");
var testClass = test.className;

testClass = ( testClass == "first") ? "second" : "first";

尝试:

document.getElementById('id').style.border

Try

// showing

document.getElementById('element').style.border = 'red';

// hiding

document.getElementById('element').style.border = 'none';
var img = document.getElementById('image-id');
img.style.border = img.style.border ? "" : "2px solid red";

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