【问题标题】:jquery: resize images in proportion data()-method?jquery:按比例数据()方法调整图像大小?
【发布时间】:2011-05-27 02:51:53
【问题描述】:

我有以下代码,我在其中检查 onload 图像的原始大小:

        $(".post-body img").each(function() {  
            $(this).data('width', $(this).width());
            $(this).data('height', $(this).height());
        });

之后,我将所有图像的大小调整为父 div .post-body 的宽度。

var bw = $('.post-body').width();
$(".post-body img").each(function() {
        // Check the width of the original image size
        if (bw < $(this).data('width')) {
            $(this).removeAttr('height');
            $(this).attr( 'width', bw ); 
            //$(this).attr( 'height', height-in-ratio ); 
        }
});

这很好用!所以我正在检查 .post-body 宽度是否小于图像的原始宽度,我将图像的大小调整为与 div 相同的宽度。

但是我认为这在某些旧版本的 Internet Explorer 中有点问题,因为我正在删除图像的高度属性。

如果存储旧的宽度和高度,计算图像比例高度的最简单方法是什么?我有一个新的宽度,我想计算合适的高度。

我似乎找不到简单的数学解决方案。

同样,我不想从图像中删除高度属性,而是计算比例高度。

感谢您的提示。 问候

【问题讨论】:

    标签: jquery math height width


    【解决方案1】:
    var newHeight = newWidth / oldWidth * oldHeight;
    

    newWidth / oldWidth 为您提供调整大小的比例。如果原始宽度为 800,新宽度为 400,则该比率变为 0.5。如果您的原始高度是 600,然后将其乘以这个比率,则得到 300。800x600 与 400x300 的比率相同。

    【讨论】:

    • 你觉得设置 width height 和 style="width; 和 height 会更好吗?
    • @user239831,使用$(this).width(newWidth)$(this).height(newHeight)
    猜你喜欢
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 2011-12-29
    • 2017-09-04
    • 1970-01-01
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多