Getting image width on image load fails on IE

后端 未结 8 1446
自闭症患者
自闭症患者 2020-12-31 09:32

I have a image resizer function that resize images proportional. On every image load a call this function with image and resize if its width or height is bigger than my max

8条回答
  •  南笙
    南笙 (楼主)
    2020-12-31 10:20

    This is how I solved it (because it's the only js on the site I didn't want to use a library).

        var imageElement = document.createElement('img');
        imageElement.src = el.href; // taken from a link cuz I want it to work even with no script
        imageElement.style.display      = 'none';
    
        var imageLoader = new Image();
        imageLoader.src = el.href;
        imageLoader.onload = function() {
            loaderElement.parentElement.removeChild(loaderElement);
            imageElement.style.position     = 'absolute';
            imageElement.style.top          = '50%';
            imageElement.style.left         = '50%';
            // here using the imageLoaders size instead of the imageElement..
            imageElement.style.marginTop    = '-' + (parseInt(imageLoader.height) / 2) + 'px';
            imageElement.style.marginLeft   = '-' + (parseInt(imageLoader.width) / 2) + 'px';
            imageElement.style.display      = 'block';
        }
    

提交回复
热议问题