Changing Images src with Event “onclick”

前端 未结 5 1473
谎友^
谎友^ 2021-01-13 18:54








        
相关标签:
5条回答
  • 2021-01-13 19:19

    Here is the solution:

    <!DOCTYPE html>
    <html>
        <body>
    
            <img id ="imageOne" src ="circleRed.png" onclick = "changeColor()"/>
    
            <script>
                var image =  document.getElementById("imageOne");
    
                function changeColor()
                {
                    if (image.getAttribute('src') == "circleRed.png")
                    {
                        image.src = "circleBlue.png";
                    }
                    else
                    {
                        image.src = "circleRed.png";
                    }
                }
            </script>
        </body>
    </html>
    
    0 讨论(0)
  • 2021-01-13 19:31
    var image = document.getElementById("imageOne"); 
    

    Move this inside function before if statement

    0 讨论(0)
  • 2021-01-13 19:38

    try this code. just make sure to use (img.src.match) .And script inside the body.

    var img = document.getElementById("image1");
    img.addEventListener("mouseover", function(){
          if(img.src.match("images/image1.jpg")){
               img.src ="images/image1_2.jpg";}
           else {
               img.src = "images/image1.jpg"
                }  
    })
    

    <img src="images/image1.jpg" id="image1" />

    0 讨论(0)
  • 2021-01-13 19:40

    function changeColor(image) {
        if (image.src.indexOf("circleRed.png")>-1) {
            image.src = "circleBlue.png"; 
        } else {
            image.src = "circleRed.png";
        }
    }
    <img id = "imageOne" src = "circleRed.png" onclick = "changeColor(this)"/>

    0 讨论(0)
  • 2021-01-13 19:44

    image.src returns the physical path of image. So you can use indexOf to match image name. Following code snippet may help you.

    function changeColor(image) {
        if (image.src.indexOf("circleRed.png")>-1) {
            image.src = "circleBlue.png"; 
        } else {
            image.src = "circleRed.png";
        }
    }
    <img id = "imageOne" src = "circleRed.png" onclick = "changeColor(this)"/>

    0 讨论(0)
提交回复
热议问题