Javascript 检测 img src 更改

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10655531/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:23:10  来源:igfitidea点击:

Detect a img src change

javascriptimageonchangesrc

提问by Sporting Gool

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 to detect the src change from a img element.

在我的情况下,src 是从 jquery 更改的,我无权更改 jquery 文件。所以我试图从 img 元素检测 src 变化。

I would like to see the source if the src is changed, just for testing

如果src改变了,我想看看源,只是为了测试

This is my current code:

这是我当前的代码:

var divimg = document.getElementById("img_div");
divimg.onchange = alert(divimg.getElementsByTagName('img')[0].src);

On the page load the alert react's and shows me the src, but not on a src change from jquery

在页面上加载警报反应并向我显示 src,但不在 jquery 的 src 更改上

回答by alex

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

你可以这样做,但是它只会被实现DOM 突变事件的新浏览器支持......

divimg.addEventListener("DOMAttrModified", function(event) {
    if (event.attrName == "src") {
       // The `src` attribute changed!
    }
});

回答by Parth Thakkar

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

DOMAttrModified可能有用,不知道……但 onload 对我来说绝对没问题。这是演示的小提琴。http://jsfiddle.net/QVqhz/

回答by Joseph Moniz

Every time the srcattribute 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 loadedevent on the image element. So you can effectively monitor srcchanging by setting a callback on this event. You could do something similar to the following code example.

每次src更改属性时,浏览器都会立即关闭并获取图像。一旦图像返回到浏览器,浏览器将loaded在图像元素上触发事件。所以你可以src通过在这个事件上设置回调来有效地监控变化。您可以执行类似于以下代码示例的操作。

var img = $("<img />");
img.load(function() { console.log("loaded"); });
img.attr("src", "http://static.adzerk.net/Advertisers/ecc536e9e1204b7faccb15621f27d7bc.jpg");

回答by Dorian Andrés

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});

回答by Chemical Programmer

Analysis

分析

  1. loadevent is triggered when srcattribute of <img />is changed or set

  2. If user didn't write srcattribute in <img />, browser will fill out srcattribute automatically (such as data:image/png;base64,...) to prevent 204 Error. This will also trigger loadevent.

  1. load更改或设置src属性时触发事件<img />

  2. 如果用户没有在 中写入src属性<img />,浏览器会src自动填写属性(例如 data:image/png;base64,...)以防止 204 错误。这也会触发load事件。

Conclusion

结论

  1. Basically use loadevent, but check whether it is default image or not. (Probably, default image would be 1 x 1 pixel)

    • Assumption - your image is bigger than 1 x 1 pixel
  1. 基本上使用load事件,但检查它是否是默认图像。(可能,默认图像将是 1 x 1 像素

    • 假设 - 您的图像大于 1 x 1 像素

Solution

解决方案

$('img').load(function() {
    var imageObj = $(this);
    if (!(imageObj.width() == 1 && imageObj.height() == 1)) {
        console.log('Image source changed');
    }
});

回答by Wouter J

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
}