我试图将任何大小的图像放入(始终)方形 div 中,并在父 div 的大小发生变化时保留外观。这就是我正在做的:
CSS:
.photo_container {
width: 250px;
height: 250px;
overflow: hidden;
border-style: solid;
border-color: green;
float:left;
margin-right:10px;
position: relative;
}
.photo_container a img{
position:absolute;
}
HTML
<!--p>Photo's height>width </p-->
<div class="photo_container">
<a href="#">
<img class="photo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/ECurtis.jpg/224px-ECurtis.jpg"
style="width:100%; height:auto;">
</img>
</a>
</div>
<!--p>Photo's width>height </p-->
<div class="photo_container">
<a href="#">
<img class="photo" src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/220px-Altja_j%C3%B5gi_Lahemaal.jpg"
style="width:auto; height:100%;left=-100px">
</img>
</a>
</div>
JavaScript:
// fix image size on load
$(".photo").one("load", function() {
fixImage($(this));
}).each(function() {
if(this.complete) $(this).load();
});
// Just to test if everything's working fine
$(".photo").on("click",function(){
var rand = Math.floor(Math.random() * 200) + 80;
$(this).parent().parent().width(rand);
$(this).parent().parent().height(rand);
fixImage($(this));
});
// Brings the photo dead center
function fixImage(obj){
//alert("something changed");
var pw = obj.parent().parent().width();
var ph = obj.parent().parent().height();
var w = obj.width();
var h = obj.height();
console.log(w+" "+pw);
if(h>w){
var top = (h-ph)/2;
obj.css("top",top*-1);
}else{
var left = (w-pw)/2;
obj.css("left",left*-1);
}
}
工作示例:http://jsfiddle.net/vL95x81o/4
不使用jquery而只使用CSS如何做到这一点?如果 div 的大小永远不会改变,那么这个解决方案就很好。但我正在研究响应式设计,看起来像photo_container
div 可能需要根据屏幕的大小进行更改(通过 CSS)。
以下是裁剪前的照片:
你可以这样做:
http://jsfiddle.net/vL95x81o/5/
<!--p>Photo's height>width </p-->
<div class="photo_container">
<div class="photo photo--1">
</div>
</div>
<!--p>Photo's width>height </p-->
<div class="photo_container">
<div class="photo photo--2">
</div>
</div>
.photo_container {
width: 250px;
height: 250px;
overflow: hidden;
border-style: solid;
border-color: green;
float:left;
margin-right:10px;
position: relative;
}
.photo {
height: 100%;
width: 100%;
}
.photo--1 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/5/57/ECurtis.jpg/224px-ECurtis.jpg') no-repeat center center;
background-size: cover;
}
.photo--2 {
background: url('https://upload.wikimedia.org/wikipedia/commons/thumb/c/c8/Altja_j%C3%B5gi_Lahemaal.jpg/220px-Altja_j%C3%B5gi_Lahemaal.jpg') no-repeat center center;
background-size: cover;
}
我已将 imgs 更改为带有背景图像的 div,并使用背景位置覆盖,图像居中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)