IE8 non-compatibility mode, image with max-width and height:auto

后端 未结 6 1038
清酒与你
清酒与你 2020-12-24 06:22

I have an image with this markup


And I am using CSS to downsize it to 600

6条回答
  •  太阳男子
    2020-12-24 06:35

    Wow, what a pain IE always seems to be. Although there is an accepted answer, I found that it did not solve my problem.

    After much search I found that the way to fix it is to remove the height and width attributes from the images in question. An explanation can be found here: Scaling Images in IE8 with CSS max-width

    The code is as follows:

    CSS:

    .entry img {
        max-width:615px
        height:auto;
    }
    

    SCRIPT

    var imgs, i, w;
    var imgs = document.getElementsByTagName( 'img' );
    for( i = 0; i < imgs.length; i++ ) {
        w = imgs[i].getAttribute( 'width' );
        if ( 615 < w ) {
            imgs[i].removeAttribute( 'width' );
            imgs[i].removeAttribute( 'height' );
        }
    }
    

    Now I tend to use jQuery as much as possible, to solve this I used a few different functions to target IE8 and make my life easier. I also found that the solution almost worked, but not quite. I toyed around with it until I was able to achieve the results I was looking for. My solution is as follows:

    JQUERY:

    var maxWidth = 500;
    
    function badBrowser(){
    if($.browser.msie && parseInt($.browser.version) <= 8){
        return true;
    }   
        return false;
    }
    
    
    if(badBrowser()){
        $('img').each(function(){
            var height = $(this).height();
            var width = $(this).width();
            if (width > maxWidth) {
    
                var ratio = (maxWidth /width)  
                $(this).css({
                    "width":maxWidth,               
                    "height":(ratio*height)
                });
                $(this).removeAttr('width'); 
                $(this).removeAttr('height');
            }else{
                $("#cropimage").css({
                    "width":width,               
                    "height":height
                });
            }
        });       
    }
    

    I use this to target a specific image load function, but it could be added to any document ready or window load function as well.

提交回复
热议问题