Detect a img src change

前端 未结 7 1505
被撕碎了的回忆
被撕碎了的回忆 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 17:16

    Analysis

    1. load event is triggered when src attribute of <img /> is changed or set

    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. This will also trigger load event.

    Conclusion

    1. Basically use load event, 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

    Solution

    $('img').load(function() {
        var imageObj = $(this);
        if (!(imageObj.width() == 1 && imageObj.height() == 1)) {
            console.log('Image source changed');
        }
    });
    
    0 讨论(0)
提交回复
热议问题