Jquery调整图像大小

标签 jquery image

我想开始讨论使用 jQuery 调整图像大小。

这就是我的贡献:但我认为我距离解决方案还很远。 裁剪怎么样? 谁能帮助我?

$(document).ready(function() {
    $('.story-small img').each(function() {
    var maxWidth = 100; // Max width for the image
    var maxHeight = 100;    // Max height for the image
    var ratio = 0;  // Used for aspect ratio
    var width = $(this).width();    // Current image width
    var height = $(this).height();  // Current image height

    // Check if the current width is larger than the max
    if(width > maxWidth){
        ratio = maxWidth / width;   // get ratio for scaling image
        $(this).css("width", maxWidth); // Set new width
        $(this).css("height", height * ratio);  // Scale height based on ratio
        height = height * ratio;    // Reset height to match scaled image
    }

    // Check if current height is larger than max
    if(height > maxHeight){
        ratio = maxHeight / height; // get ratio for scaling image
        $(this).css("height", maxHeight);   // Set new height
        $(this).css("width", width * ratio);    // Scale width based on ratio
        width = width * ratio;    // Reset width to match scaled image
    }
});

});

最佳答案

您需要在第一个条件后重新计算宽度和高度。这是整个脚本的代码:

$(document).ready(function() {
    $('.story-small img').each(function() {
    var maxWidth = 100; // Max width for the image
    var maxHeight = 100;    // Max height for the image
    var ratio = 0;  // Used for aspect ratio
    var width = $(this).width();    // Current image width
    var height = $(this).height();  // Current image height

    // Check if the current width is larger than the max
    if(width > maxWidth){
        ratio = maxWidth / width;   // get ratio for scaling image
        $(this).css("width", maxWidth); // Set new width
        $(this).css("height", height * ratio);  // Scale height based on ratio
        height = height * ratio;    // Reset height to match scaled image
    }

    var width = $(this).width();    // Current image width
    var height = $(this).height();  // Current image height

    // Check if current height is larger than max
    if(height > maxHeight){
        ratio = maxHeight / height; // get ratio for scaling image
        $(this).css("height", maxHeight);   // Set new height
        $(this).css("width", width * ratio);    // Scale width based on ratio
        width = width * ratio;    // Reset width to match scaled image
    }
});

关于Jquery调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1143517/

相关文章:

javascript - 加载前调整图像大小 - jquery

Android:如何将生成的临时图像附加到电子邮件中?

javascript - 如果 Django 和 Bootstrap 中存在用户名,则返回错误消息

javascript - 使用 RowCommand 事件在 GridView 上编辑单击弹出 Bootstrap 模型

javascript - 谁可以帮助我自动完成

javascript - 用 jQuery 精美框替换默认浏览器确认

image - 在不可见区域绘制 VSIS 图像位图

c# - 使用 Azure Web 部署时保存到 Azure 根文件夹

css - 最大高度为 :100% stretches table with manually set height 的图片

javascript - 将对象数据插入 JSON 文件