更改img高度,使其's具有一定的纵横比's宽度
Change an img height so it's at a certain aspect ratio to it's width with jQuery
我有一个图像,需要使用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
相关文章:
- 只在宽度以下和宽度以上各准备一次
- 如何基于具有动态宽度的父容器设置比例宽度
- 获取/保留上一页's具有SmoothState的URL
- 有没有一种方法可以让我得到window.onresize只刷新页面的宽度大小
- 从一组具有相同起始和结束的所有段落的段落中提取包含特定字符串的段落
- 将具有两个此类子字符串的字符串中的第一个子字符串生成与正则表达式匹配,正则表达式通常默认匹配最后一个子字符串
- 如何使用Java脚本获取具有相同ID的多个图像的高度和宽度
- 如何将具有多个标签的多个的所有数据获取到一个数组中
- 在JavaScript / jQuery中,是否有一种更短的方法可以编写在同一个测试变量上具有许多OR的“if”语句
- 找到具有最大文本的选项的宽度
- JavaScript选项卡动态宽度.animate()只能工作一次
- 一种在javascript上获得具有两个输入(字符串)的散列键的方法
- jQuery datepicker 解析具有一位数的年份
- ui路由器——具有一条路由'的URL与另一个具有$stateParams的状态共享同一级别
- 创建具有一个数组属性的Javascript对象
- 数组中具有一组值的循环迭代
- 如何仅查找集合中具有一组ID的最新文档
- AngularJS的设计模式与具有一组公共字段的2个服务一起使用
- 将已定义的函数赋值给具有一组参数的变量
- Dgrid 在具有一列的数据源上执行更新