Toggle image src attribute using Javascript

后端 未结 3 720
时光说笑
时光说笑 2020-12-10 22:22

I am trying to change the HTML image src using Javascript. I have two images Plus.gif and Minus.gif.I have inserted HTML img tag and have written a

3条回答
  •  有刺的猬
    2020-12-10 23:00

    One way would be to add a toggle variable in your function:

    var toggle = false;
    function chngimg() {
        if (toggle === true) {
            document.getElementById('imgplus').src  = 'Images/Minus.gif';
        } else {
           document.getElementById('imgplus').src = 'Images/Plus.gif';
           alert(img); 
        }
        toggle = !toggle; 
    }
    

    Note that it's a better practice to use a sprite for this kind of thing. If you're using two images, the user experience is going to be clunky, because the first time they click the image, there will be a slight delay while the second image loads.

    Ideally you would have the two images as a sprite sheet, and be using JQuery. Then you could just do it like this.

    HTML

    
    

    CSS

    #imgplus .clicked { background-position: 0 -30px; }
    

    Javascript

    function chngimg() {
        $("#imgplus").toggleClass("clicked");
    }
    

提交回复
热议问题