Javascript 使用jQuery更改img高度,使其与宽度具有一定的纵横比
我有一个图像,我需要用jQuery更改它的维度。图像宽度应与其父div的宽度相同。父div是一个响应列容器,因此其宽度为dynamicfluid。一旦图像的宽度改变,高度也应改变为与图像宽度的16:9纵横比相对应的值。假设列宽是1920。。。然后图像高度将为1080。如何修改代码以实现此目的Javascript 使用jQuery更改img高度,使其与宽度具有一定的纵横比,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有一个图像,我需要用jQuery更改它的维度。图像宽度应与其父div的宽度相同。父div是一个响应列容器,因此其宽度为dynamicfluid。一旦图像的宽度改变,高度也应改变为与图像宽度的16:9纵横比相对应的值。假设列宽是1920。。。然后图像高度将为1080。如何修改代码以实现此目的 $(document).ready(function(){ $('#featured-articles').find('.featured').each(function(){ v
$(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);
加宽度:100%;到你的img css。这自然保持了原始图片的纵横比,假设原始图片的纵横比为16:9,这是一个非常有效的假设,因为您不应该拉伸/破坏图像
img {
width: 100%;
}
这里有一个简单的例子: 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>
你可以试试这个例子太完美了!谢谢是的,这些图像将由用户上传,我的表单需要精确的尺寸,但很少有机会图像未经验证就通过,这将填充div。
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);