简体   繁体   中英

Resize images above max width

JavaScript would probably do it, I have searched but found nothing to do with maxWidth. Only resizing images out of the blue.

What I need is a piece of JavaScript code to resize an image if it's too big(defined in a variable.)

Is there some reason why you can't use the max-width CSS property to do what you want, like:

<img src="myImage.png" style="max-width: 600px;">

...or even better:

<style>
    .widthConstrained {
        max-width: 600px; 
    }
</style>

...

<img src="myImage.png" class="widthConstrained">

Edit:

If you must use JavaScript for compatibility reasons, I suggest that you use something like the code specified in this question to check the total image width after it loads, and clamp it down if needed, roughly like:

var img = $("img")[0]; // Get my img elem
$("<img/>") // Make in memory copy of image to avoid css issues
    .attr("src", $(img).attr("src"))
    .load(function() {
        if (this.width > maxWidth) {
            $(img).width(maxWidth);
        }
    });

I take it you have a <img /> tag in your webpage.

To shrink images that are too large, simply insert the width and height attribute, along with your image source and a alt, along with a ID.

<head>
    <script type="text/javascript" />
       function pie()
       {
        var pathToImage = "bla/bla/Image.jpg";
        document.GetElementByID(Image1).setAttribute("src",pathToImage);
       }
    </script>
</head>
<body onload=Pie() >
    <img ID="Image1" alt="random Image" width="300px" Height="200px" />
</body>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM