javascript - jQuery 调整大小以适应纵横比

标签 javascript jquery image scale

我如何将 jQuery 中的图像调整为一致的纵横比。例如设置最大高度并正确调整宽度。谢谢。

最佳答案

这是一个有用的函数,可以满足您的需求:

jQuery.fn.fitToParent = function()
{
    this.each(function()
    {
        var width  = $(this).width();
        var height = $(this).height();
        var parentWidth  = $(this).parent().width();
        var parentHeight = $(this).parent().height();

        if(width/parentWidth < height/parentHeight) {
            newWidth  = parentWidth;
            newHeight = newWidth/width*height;
        }
        else {
            newHeight = parentHeight;
            newWidth  = newHeight/height*width;
        }
        var margin_top  = (parentHeight - newHeight) / 2;
        var margin_left = (parentWidth  - newWidth ) / 2;

        $(this).css({'margin-top' :margin_top  + 'px',
                     'margin-left':margin_left + 'px',
                     'height'     :newHeight   + 'px',
                     'width'      :newWidth    + 'px'});
    });
};

基本上,它会抓取一个元素,将其置于父元素的中心,然后将其拉伸(stretch)以适应父元素的背景不可见,同时保持宽高比。

话又说回来,这可能不是你想要做的。

关于javascript - jQuery 调整大小以适应纵横比,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1682495/

相关文章:

javascript - d3.js:序数尺度

javascript - 为什么我的变量值在 Logger.log 中发生变化

javascript - Jquery 将按钮值中的字符串添加到输入字段中

jquery - 使用 jquery 将 css3 选择器添加到 Internet Explorer 的最小 javascript 库

php - 尝试从数据库中获取多个图像,但多次只获取第一个图像

html - 来自较低文件夹的图像链接不起作用

javascript - ng-click 事件不适用于 ocLazyLoad

jquery - 使用 JQuery 设置表单元素的样式

JavaScript slider jquery

css - 将文本对齐到图像的右侧 && 文本不会环绕图像