简体   繁体   English

如果已经在HTML中设置了宽度和高度,您可以使用CSS(或JS / JQ)按比例调整图像大小

[英]Can you proportionally resize an image with CSS (or JS/JQ) if width & height are already set in HTML

Is there a way to proportionally resize an image if the height and width are already defined in the tag? 如果已在标签中定义了高度和宽度,是否有办法按比例调整图像大小?

Obviously, if I have an image tag like: 显然,如果我有一个像这样的图像标签:

<img src="whatever.jpg" width="500" height="350">

and use max-width like: 并使用max-width,如:

img { max-width: 200px; }

I'll end up with an image that is 200px by 350px. 我最终会得到一张200像素×350像素的图像。

I'd prefer a pure CSS solution (which I'm fairly sure does not exist), but might also be able to use some Javascript and/or jQuery. 我更喜欢纯CSS解决方案(我相当确定不存在),但也可能使用一些Javascript和/或jQuery。

Ofcourse, you set the other dimension to auto : 当然,您将另一个维度设置为auto

img{
    height:auto;
    width:200px;
}

I don't think CSS can do that. 我不认为CSS可以做到这一点。

With jQuery, it's trivial. 使用jQuery,它是微不足道的。 You don't even need the width and height attributes in the HTML, though it's usually good to have them. 你甚至不需要HTML中的width和height属性,尽管通常它们很好。

$("img").each(function(){
    var real_width = $(this).width();
    var real_height = $(this).height();
    var max_width = $(this).css("max-width");  // Or just say 200
    if (real_width > max_width) {
        var ratio = real_width / real_height;
        $(this).width(max_width);
        $(this).height(max_width / ratio);
    }
});

I haven't tested this code so there might be minor bugs, but the general idea is there. 我没有测试过这段代码,所以可能会有一些小错误,但总的想法是存在的。

Edit: On some browsers, $(document).ready() will fire before all the images have been loaded. 编辑:在某些浏览器上, $(document).ready()将在加载所有图像之前触发。 If you have an image without explicit width and height attributes, this can be a problem because $(this).width() will return 0. In that case, just ensure that all images have width and height attributes, or attach this code to $("img").load() instead. 如果您的图像没有明确的宽度和高度属性,这可能是一个问题,因为$(this).width()将返回0.在这种情况下,只需确保所有图像都有width和height属性,或者将此代码附加到$("img").load()代替。

// parameters
// obj      : usually $('img') object I presume.
function thumbnail_resize(obj){
    var maxW = 50;      var maxH = 50;
    var wid = obj.width();
    var hei = obj.height();

    if( wid > maxW ) {
        hei *= (maxW / wid);
        wid = maxW;
    }
    if( hei > maxH ) {
        wid *= (maxH / hei);
        hei = maxH;
    }
    obj.attr('width', wid);
    obj.attr('height', hei);

    delete maxW, maxH, wid, hei;
    return;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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