2017-09-15 109 views
0

我需要在我的应用程序中插入图像到给定大小的方形div,我希望它们显示完整,而不裁剪任何部分。目前,我有一个JavaScript代码,如果图像是纵向(高度>宽度),然后将高度设置为100%,宽度设置为自动,如果它是横向(宽度>高度)设置宽度为100%,高度为汽车将图像大小调整为平方div保持长宽比

http://jsfiddle.net/z7L6m2sc/583/

这是我试图复制我的代码(这是在该局及咖啡,因为我正在开发一个Rails应用程序,我不知道为什么,但图像没有内部中心的链接股利(在我的应用程序的代码的伟大工程!)

这是我在Rails代码

ERB

<div class="img"> 
    <% if i.insertion_images.length > 0 %> 
    <%= image_tag(i.insertion_images[i.first_img].image.url(:medium), class: 'last_img')%> 
    <% end %> 
</div> 

这是咖啡

$('.last_img').on 'load', -> 
     natHeight = $(this).get(0).naturalHeight 
     natWidth = $(this).get(0).naturalWidth 
     if (natWidth > natHeight) 
     $(this).css('width','100%') 
     $(this).css('height','auto') 
     else #if (natWidth < natHeight) 
     $(this).css('height','100%') 
     $(this).css('width','auto') 

这是SCSS

img { 
     width: 200px; 
     height: 200px; 
     overflow: hidden; 
     position: relative; 
     last_img { 
     position: absolute; 
     top: -9999px; 
     bottom: -9999px; 
     left: -9999px; 
     right: -9999px; 
     margin: auto; 
     } 
    } 

我开始使用Flex为我的布局,所以我的问题是,是否有可能实现与柔性此行为零件?也许没有所有的JS代码和CSS中-9999

感谢

回答

0

你可以在.image-resize使用max-height: 100%max-width: 100%,我相信它会给你,你之后的结果。如果您想要安全,您还可以添加width: autoheight: auto

.img-container{ 
 
    height: 300px; 
 
    width: 300px; 
 
    overflow: hidden; 
 
    background:red; 
 
    position: relative; 
 
} 
 

 
.image-resize { 
 
    max-width: 100%; 
 
    max-height: 100%; 
 
    height: auto; 
 
    width: auto; 
 
}
<div class="img-container"> 
 
    <img src="http://s.hswstatic.com/gif/landscape-photography-1.jpg" class="image-resize"/> 
 
</div> 
 
<hr> 
 
<div class="img-container"> 
 
    <img src="https://i.pinimg.com/736x/05/1c/11/051c110d463b1c4afb11ca003a6237a3--nice-girl-beautiful-body.jpg" class="image-resize"/> 
 
</div>

0

为此,您可以使用CSS,如果你不介意设置图像作为背景。

.bg-image{ 
 
    height: 300px; 
 
    width: 300px; 
 
    background-color: red; 
 
    background-size: contain; 
 
    background-repeat: no-repeat; 
 
    background-position: center; 
 
    display: inline-block; 
 
}
<div class="bg-image img-1" style="background-image: url(http://s.hswstatic.com/gif/landscape-photography-1.jpg)"></div> 
 
<div class="bg-image img-2" style="background-image: url(https://i.pinimg.com/736x/05/1c/11/051c110d463b1c4afb11ca003a6237a3--nice-girl-beautiful-body.jpg)" ></div>

相关问题