简体   繁体   中英

jQuery image/window resize--max resize constraint

I currently have a page where I have fixed-size divs that load pages as a user scrolls down (similar to Infinite Scroll) and am currently working on functionality to have the loaded images and containers dynamically resize along with the browser window. My current issue is that I'm currently using $(window).width and $(window).height , which naturally causes the images to resize to the window width.

I was wondering what I can set maxWidth and maxHeight to so that the images don't get resized any greater than their original size? I've been using $(window) just to test the function, but I basically don't want the images to become any larger than their original size. I've tried $(this) , but it causes the ratio to be equal to 1, resulting in no resize.

    $(window).resize(function () {
        imageResize();
    });

    function imageResize() {
        $(".added").each(function () {
                var maxWidth = $(window).width();
                var maxHeight = $(window).height();
                var ratio = 0;
                var width = $(this).width();
                var height = $(this).height();

                if (width > maxWidth) {
                    ratio = (maxWidth / width);
                    $(this).width(maxWidth);
                    $(this).height(height * ratio);
                    $(this).parent().height(height * ratio);
                    $(this).parent().width(maxWidth);   
                } else {
                    ratio = (maxWidth / width);
                    $(this).width(maxWidth);
                    $(this).height(height * ratio);
                    $(this).parent().height(height * ratio);
                    $(this).parent().width(maxWidth);   
                }
        });
    }

我将样式更改为:($ this).style.maxWidth = maxWidth;

You want to set the max-height and max-width properties to the values you said, this will not force the image to grow further than their original height or width and will minimize it if it is larger.

Use:

$("#imageId").attr("max-width",maxWidth);
$("#imageId").attr("max-height",maxHeight);

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