Detect a img src change

前端 未结 7 1504
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 16:20

I\'am trying to detect if the source of a image is changed.

In my case the src is changed from jquery, and i have no right\'s to change the jquery file. So im trying

相关标签:
7条回答
  • 2020-12-16 16:52

    You could do it, however it would only be supported by new browsers that implement the DOM mutation events...

    divimg.addEventListener("DOMAttrModified", function(event) {
        if (event.attrName == "src") {
           // The `src` attribute changed!
        }
    });
    
    0 讨论(0)
  • 2020-12-16 16:53

    Every time the src attribute is changed the browser will immediately go off and fetch the image. Once the image is returned to the browser the browser will trigger the loaded event on the image element. So you can effectively monitor src changing by setting a callback on this event. You could do something similar to the following code example.

    var img = $("<img />");
    img.load(function() { console.log("loaded"); });
    img.attr("src", "http://static.adzerk.net/Advertisers/ecc536e9e1204b7faccb15621f27d7bc.jpg");
    
    0 讨论(0)
  • 2020-12-16 17:00

    DOMAttrModified might work, no idea about that...but onload works definitely fine for me. Here's the fiddle with the demo. http://jsfiddle.net/QVqhz/

    0 讨论(0)
  • 2020-12-16 17:02

    I think there is no event for that, you can create your own 'event':

    var divimg = document.getElementById("img_div"),
        prevSrc;
    setInterval(function() {
        if (divimg.src != prevSrc) {
            prevSrc = divimg.src;
            onSrcChange();
        }
    }, 1000); // 1000ms = 1s
    
    function onSrcChange() {
        // do something
    }
    
    0 讨论(0)
  • 2020-12-16 17:02

    I believe that jQuery should always be the way to go because of its cross-browser support. However the ".load()" function has been deprecated since jQuery 1.8.

    Today we are supposed to use the ".on()" function like the following example:

    $('img.my-image-class-name').on('load', function(){
      console.log('Hello, world');
    });
    

    If you attempt to use the ".load()" function, your code will simply not work. You will get the following error message:

    Uncaught TypeError: a.indexOf is not a function

    0 讨论(0)
  • 2020-12-16 17:04
    var img = document.querySelector("#img_div img"),
    observer = new MutationObserver((changes) => {
      changes.forEach(change => {
          if(change.attributeName.includes('src')){
            console.dir(img.src);
          }
      });
    });
    observer.observe(img, {attributes : true});
    
    0 讨论(0)
提交回复
热议问题