IMG SRC tags and JavaScript

前端 未结 13 1231
眼角桃花
眼角桃花 2020-12-02 02:09

Is it possible to call a JavaScript function from the IMG SRC tag to get an image url?

Like this:





        
13条回答
  •  醉酒成梦
    2020-12-02 02:14

    Is it possible to call a JavaScript function from the IMG SRC tag to get an image url?

    Do you mean doing something like the following?

    
    

    Unfortunately, no - you can't do that. However, you can do the following hack:

    function getImageUrl(img) {
       var imageSrc = "imageName/imagePath.jpg";
       if(img.src != imageSrc) { // don't get stuck in an endless loop
          img.src = imageSrc;
       }
    }
    

    Then, have the following html:

    
    

    The onload event will only fire if you have an actual image set to the src attribute - if you don't set that attribute or set it to an empty string or something similar, you will get no love. Set it to a single pixel transparent gif or something similar.

    Anyway, this hack works, but depending on what you are really trying to accomplish, this may not be the best solution. I don't know why you would want to do this, but maybe you have a good reason (that you would like to share with us!).

提交回复
热议问题