自动以原始比例改变图像大小,同时改变图像父元素的大小 [英] automatically change the image size in the original ratio of the while change the size of that images parent element

查看:170
本文介绍了自动以原始比例改变图像大小,同时改变图像父元素的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

div标签有一个图像。我必须改变div的宽度和高度。如果我改变标签的宽度和高度,那个图像的宽度和高度会以图像的原始比例自动改变。大小不能超过原始大小,使用jQuery或Javascript。

A div tag have a image.I have to change the div width and height.If I change the width and height of the tag, that image's width and height will be automatically change in the original ratio of image.But, image size should not exceed than original size,using jQuery or Javascript.

<div>
    <img src="logo.jpg"/>
</div>


推荐答案

您可能想在 window.load

$('img:visible').each(function() {
    // For visible images only
    var imageWidth,
        imageHeight,
        aspectRatio;

    var parentWidth = $(this).parent().width(),
        parentHeight = $(this).parent().height();

    if (this.naturalWidth > parentWidth || this.naturalHeight > parentHeight) {
        aspectRatio = this.naturalWidth / this.naturalHeight; // Actual image width and height

        if (this.naturalWidth > this.naturalHeight) {
            imageWidth = parentWidth - 50; // Leave margin
            imageHeight = imageWidth / aspectRatio;
        } else {
            imageHeight = parentHeight - 10; // Leave some space
            imageWidth = imageHeight * aspectRatio;
        }

        $(this).css({
            'width': imageWidth,
            'height': imageHeight
        });
    }
});

演示: https://jsfiddle.net/tusharj/onytgawp/

这篇关于自动以原始比例改变图像大小,同时改变图像父元素的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆