簡體   English   中英

使用寬高比調整圖像大小

[英]resizing image with aspect ratio

我正在嘗試調整圖像的大小,但不希望將其增加到其原始大小以上-我也想將圖像居中放置在其容器內。 這是做這件事的最佳方法,因為有時看起來有些生澀?

我已經刪除了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 1.7.2版中正常運行

使用“ CENTER”模式檢查我的插件是否正確: https : //github.com/stereoactivo/jquery.resize-image-aspect-ratio

我在這種情況下使用max-width:100%; 而不是width:100%;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM