HTML - display an image as large as possible while preserving aspect ratio

前端 未结 8 951
孤城傲影
孤城傲影 2020-12-28 16:44

I\'d like to have an HTML page which displays a single PNG or JPEG image. I want the image to take up the whole screen but when I do this:



        
相关标签:
8条回答
  • 2020-12-28 17:45

    Here's a quick function that will adjust the height or width to 100% depending on which is bigger. Tested in FF3, IE7 & Chrome

    <html>
    <head>
    <script>
    function resizeToMax(id){
        myImage = new Image() 
        var img = document.getElementById(id);
        myImage.src = img.src; 
        if(myImage.width > myImage.height){
            img.style.width = "100%";
        } else {
            img.style.height = "100%";
        }
    }
    </script>
    </head>
    <body>
    <img id="image" src="test.gif" onload="resizeToMax(this.id)">
    </body>
    </html>
    
    0 讨论(0)
  • 2020-12-28 17:48

    For this, JavaScript is your friend. What you want to do, is on page load, walk through the dom, and for every image (or alterantively, pass a function an image id if it's just a single image) check if which attribute of the image is greater, it's height or width.

    This is the IMAGE itself, not the tag.

    Once you got that, then set the corresponding height/width on the tag to 100% and the other to auto

    some helpful code--all from off the top of my head, so your mileage may vary on the syntax..

    var imgTag = $('myImage'); 
    var imgPath = imgTag.src; 
    var img = new Image(); 
    img.src = imgPath; 
    var mywidth = img.width; 
    var myheight = img.height;
    

    As an aside, this would be a much easier task on the server side of things. On the server, you could literally change the size of the image that's getting streamed down tot he browser.

    0 讨论(0)
提交回复
热议问题