【发布时间】:2015-09-25 00:42:42
【问题描述】:
我正在尝试将任何大小的图像放入(始终)方形 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)。
以下是裁剪前的照片:
【问题讨论】:
-
你可以使用div的背景图片而不是img标签吗??
-
正如我在下面提到的,我宁愿不这样做,因为这意味着代码中的一些变化取决于具有 和
。也不确定这是否会影响 SEO,以及 Googlebot 如何获取图像。
-
这里有一些其他好的答案:stackoverflow.com/questions/10830735/…