简体   繁体   English

检测 img src 更改

[英]Detect a img src change

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.在我的情况下,src 是从 jquery 更改的,我无权更改 jquery 文件。 So im trying to detect the src change from a img element.所以我试图从 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 更改上

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

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

DOMAttrModified might work, no idea about that...but onload works definitely fine for me. DOMAttrModified可能会起作用,对此一无所知……但是 onload 对我来说绝对没问题。 Here's the fiddle with the demo.这是演示的小提琴。 http://jsfiddle.net/QVqhz/ http://jsfiddle.net/QVqhz/

Every time the src attribute is changed the browser will immediately go off and fetch the image.每次更改src属性时,浏览器都会立即关闭并获取图像。 Once the image is returned to the browser the browser will trigger the loaded event on the image element.一旦图像返回到浏览器,浏览器将在图像元素上触发loaded事件。 So you can effectively monitor src changing by setting a callback on this event.因此,您可以通过在此事件上设置回调来有效地监控src变化。 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");

Analysis分析

  1. load event is triggered when src attribute of <img /> is changed or set<img /> src属性改变或设置时触发load事件

  2. If user didn't write src attribute in <img /> , browser will fill out src attribute automatically ( such as data:image/png;base64,... ) to prevent 204 Error.如果用户没有在<img />写入src属性,浏览器会自动填写src属性(例如 data:image/png;base64,... )以防止 204 错误。 This will also trigger load event.这也会触发load事件。

Conclusion结论

  1. Basically use load event, but check whether it is default image or not.基本上使用load事件,但检查它是否是默认图像。 ( Probably, default image would be 1 x 1 pixel ) 可能,默认图像将是 1 x 1 像素

    • Assumption - your image is bigger than 1 x 1 pixel假设 - 您的图像大于 1 x 1 像素

Solution解决方案

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

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
}

I believe that jQuery should always be the way to go because of its cross-browser support.我相信 jQuery 应该始终是要走的路,因为它的跨浏览器支持。 However the ".load()" function has been deprecated since jQuery 1.8 .然而,“.load()”函数自jQuery 1.8起已被弃用。

Today we are supposed to use the ".on()" function like the following example:今天我们应该像下面的例子一样使用“.on()”函数:

$('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.如果您尝试使用“.load()”函数,您的代码将无法正常工作。 You will get the following error message:您将收到以下错误消息:

Uncaught TypeError: a.indexOf is not a function未捕获的类型错误:a.indexOf 不是函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM