我有方形DIV和大型肖像和风景图像.
我需要在DIV中将图像与额外部分相匹配 overflow:hidden
例如.如果纵向设置宽度= div高度的宽度: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');
}
});
Run Code Online (Sandbox Code Playgroud)
PS图像无法拉伸,必须缩放
像这样使用一些CSS
.magic.portrait {
height: 300px;
width: auto;
}
.magic.landscape {
width: 300px;
height: auto;
}
Run Code Online (Sandbox Code Playgroud)
并且只需用JS添加一个类
$('.magic').each(function(){
if($(this).width() > $(this).height()){
$(this).addClass('landscape');
}else{
$(this).addClass('portrait');
}
});
Run Code Online (Sandbox Code Playgroud)
这也有助于保持应用程序逻辑和样式的完美分离.更好的是,添加这些类服务器端,并完全避免使用JavaScript.