【问题标题】:Resizing height or width as percentage minus value with jQuery and maintaining aspect ratio使用 jQuery 将高度或宽度调整为百分比减值并保持纵横比
【发布时间】:2012-02-05 23:50:29
【问题描述】:

我希望图像是窗口宽度的 100%减去页眉高度及其边距。 同时,它的宽度不能超过窗口的宽度。这一点,我想我已经用下面的代码实现了:

HTML:

<header></header>

<img id="photo" src="http://farm5.staticflickr.com/4031/4718599034_5ab720d0f9_b.jpg" realwidth="1024" realheight="768" />

CSS:

header {
    position:absolute;
    top:0px;
    left:0px;
    width:300px;
    height:150px;
    background-color:#000;
    margin:20px;
}

img {
    position:absolute;
    bottom:10px;
    left:0px;
    max-width:1024px;
    max-height:768px;
    margin-right:20px;
    margin-left:20px;

}

还有,jQuery:

function setSize () {
   var windowHeight = $(window).height();
   var headerHeight = $('header').height();
   var windowWidth = $(window).width();


   $('img').height(windowHeight - headerHeight - 40);

   $('img').width(windowWidth - 40);
}


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

setSize();

Here's the JSFiddle.

我不能做的和我想做的就是保持图像的纵横比。如何做到这一点?

【问题讨论】:

    标签: jquery height width aspect-ratio


    【解决方案1】:

    如果您更改图像的 NATIVE 高度属性,而不是其 CSS 高度,宽度将自动跟随纵横比。

    $('img').attr('height',(windowHeight - headerHeight - 40)+'px');
    

    【讨论】:

    • 感谢您的建议。虽然这适用于一个维度,但它似乎并不同样适用于两个维度。也就是说,宽度会跟随高度,但高度也不会跟随宽度......
    猜你喜欢
    • 2018-10-10
    • 2011-06-08
    • 1970-01-01
    • 2014-04-17
    • 2014-07-01
    • 1970-01-01
    • 2015-01-28
    • 2020-04-23
    • 2011-04-14
    相关资源
    最近更新 更多