jquery - 按纵横比调整图像大小

标签 jquery html css

我正在尝试调整图像大小但不将其增加到超过其原始大小 - 我还想将图像置于其容器的中心。这是最好的方法,因为它有时看起来有点生涩?

我把jquery js链接去掉了

<html>
    <head>
        <style type="text/css">
            .container {
                width: 100%;
                height: 100%;
                background: #444;
            }
        </style>                
    </head>

    <body>
        <div class="container">
            <img src="D:\large.png" />
        </div>
    </body>

    <script>
        var $orig_width=0;
        var $orig_height=0;
        var width;
        var height;
        var $img;

         $(window).load(function() {            
            $img = $('.container').find('img');     
            $orig_width=$img.width();
            $orig_height=$img.height(); 
            resize();           
         });

        function resize() {
            var width=$img.width();
            var height=$img.height();       
            var parentWidth  = $img.parent().width();
            var parentHeight = $img.parent().height();

            newWidth  = parentWidth;
            newHeight = newWidth/width*height;

            if (newHeight>$orig_height) newHeight=$orig_height;     
            if (newWidth>$orig_width) newWidth=$orig_width; 

            margin_top  = (parentHeight - newHeight) / 2;
            margin_left = ((parentWidth  - newWidth ) / 2);

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

        $(window).resize(function() {           
            resize();           
        })      

    </script>

</html>

最佳答案

您只需使用表格作为容器。因为你很容易在表格中对齐它。 将固定宽度和高度设置为属性将带来固定尺寸图像的解决方案。

关于jquery - 按纵横比调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9275279/

相关文章:

html - 如何在css中进行图像裁剪

javascript - 如何在悬停在句子中的单词上时显示定义?

html - CSS inline-block 在 slider 列表中不起作用

javascript - 奇怪的 JavaScript 滚动/渲染问题

jquery - 如何解决桌面浏览器上由具有不同页面内容高度的页面之间的滚动条切换触发的背景内容抖动问题?

javascript - 如何从表格中删除表格行元素的模式?

html - 内联 CSS,为电子邮件保留 td 中的空白

javascript - 数据表数据未写入 xlsx 文件

html - 如何将页面样式应用于不同的div

css - 底部 Angular 粘性页脚