更改img高度,使其's具有一定的纵横比's宽度

Change an img height so it's at a certain aspect ratio to it's width with jQuery

本文关键字:宽度 具有一 高度 更改 img 使其      更新时间:2023-09-26

我有一个图像,需要使用jQuery更改其维度。图像宽度应该与其父div的宽度相同。父div是一个响应列容器,因此它的宽度是动态的(流体)。一旦图像的宽度改变,高度也应该改变为与图像宽度的16:9的纵横比相对应的值。假设列宽为1920…则图像高度为1080。我如何修改我的代码才能做到这一点?

$(document).ready(function(){
    $('#featured-articles').find('.featured').each(function(){
        var slide = $(this);
        $(this).find('img[rel="featured_preview"]').each(function(){
            var new_width = slide.width();
            var new_height = ?????
            $(this).prop("width", new_width).prop("height", new_height);
        });
    });
});
<div id="featured-articles">
     <div class="featured">
          <img src="slide.jpg" rel="featured_preview">
     </div>
     <div class="featured">
          <img src="slide2.jpg" rel="featured_preview">
     </div>
</div>

我还没有测试您的代码,但这是您想要的吗?

var new_height = Math.round(new_width*9/16);

width: 100%;添加到img css中。这自然地保持了原始图片的纵横比(这假设你的原始图像是16:9的比例——这是一个非常有效的假设,因为你不应该拉伸/解压缩图像)

img {
    width: 100%;
}

JSFiddle演示

这里有一个简单的例子:

html代码:

    <div id="test" style="width:300px">
        <img src="http://placehold.it/300x300" />    
   </div>
    <script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>

javascript代码(使用jquery):

        var aspectRatio = 9/16; 
        $('#test img').css('width','100%');
        var imgWidth = $('#test img').css('width');
        // we have to remove the suffix px in imgWidth otherwise we will get 
        // a NaN value when we attempt to use that value in arithmetic 
        // operations
        imgWidth = imgWidth.replace('px','');  
        // above the image width is converted from percentage format(%) to a 
        // static value for example 300px
        var newHeight = imgWidth*aspectRatio;

        $('#test img').css('height',newHeight+'px');
        console.log(imgWidth+''n');
        console.log(newHeight); 

您可以尝试示例jsfiddle