我有方形 DIV 和大型纵向和横向图像。
我需要将图像放入 DIV 中,额外的部分将 overflow:hidden
例如。如果纵向设置width=div的宽度height:auto
与 Lanscape 相反。
我试过这个脚本,但没用
$('.magic').each(function(){
if($(this).css('width')>$(this).css('height')){
$(this).css('height', '300px');
$(this).css('width', 'auto');
}
else{
$(this).css('width', '300px');
$(this).css('height', 'auto');
}
});
PS 图片不能拉伸(stretch),必须缩放
最佳答案
像这样使用一些 CSS
.magic.portrait {
height: 300px;
width: auto;
}
.magic.landscape {
width: 300px;
height: auto;
}
然后用你的 JS 添加一个类
$('.magic').each(function(){
if($(this).width() > $(this).height()){
$(this).addClass('landscape');
}else{
$(this).addClass('portrait');
}
});
这也有助于将您的应用程序逻辑和样式很好地分开。更好的是,在服务器端添加这些类,并完全避免使用 JavaScript。
关于jquery - 如何调整图像大小以适应 DIV jQuery,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15351951/