Article From:https://segmentfault.com/q/1010000015621673
Question:

Problem description

v-html When the IMG width in the HTML content is restricted, does the onload of the picture need to be generated new Image () one by one?

The original writing can only change the first one

mounted: function () {
    this.$nextTick(function () {
        var Img = new Image();
        var imgs = $("#infoContent p img");
        imgs.each(function (i, v) {
            Img.src = v.src;
            Img.onload = function() {
                if ($(v).width() > 630) {
                    $(v).css('width', '100%');
                }                                    
            }
        })
    })
}

Modified

mounted: function () {
    this.$nextTick(function () {
        var imgs = $("#infoContent p img"), Img = [];
        imgs.each(function (i, v) {
            Img[i] = new Image();
            Img[i].src = v.src;
            Img[i].onload = function() {
                if ($(v).width() > 630) {
                    $(v).css('width', '100%');
                }
            }
        })
    })
}

Is there any better way to write new for each img?

Answer 0:

Should be able to usecssTry to trymax-width
And you herejqMixed writing

Answer 1:

Originally proposed to use ref operation, but see you are using the v-html scheme is not feasible, do not know your HTML is the back end or their own splicing, if you can directly add a method on the IMG can be a very simple realization of your needs.

data() {
  return {
    html: '<img src="xxx" onload="onImgLoad(this)">',
  }
},

Define a global function outside VM to deal with

window.onImgLoad = (el) => {
  if (el.width > 630) {
    el.style.width = '100%'
  }
}

Leave a Reply

Your email address will not be published. Required fields are marked *