我试图根据屏幕大小调整网页上的图像网格大小,无论是自动确定3列还是4列。所有列的图像宽度保持相同,但高度可变。
我需要所有图像以完美的1:1.5比例调整大小,无论实际图像大小/比例如何,无需拉伸,只需切断溢出。我的第一个想法是改变" h"数学到w * 1.5
,但没有运气。
(function() {
var $K = $('#posts').css("position", "relative");
var rsz_i = undefined;
var rs z = function() {
if (rsz_i != undefined)
clearTimeout(rsz_i);
rsz_i = setTimeout(real_rsz, 100);
};
var first = true;
var real_rsz = function() {
var C = Math.ceil($("#posts-container").width() / 350);
var w = Math.ceil($("#posts-container").width() / C);
console.log("rsz", C, w);
$(".entry").css({ "width": w+"px" });
setTimeout(function() {
var col = 0, y = [], h = 0;
$(".entry").each(function() {
if (!y[col])
y[col] = 0;
$(this).css({
"position": "absolute",
"left": (col * w)+"px",
"top": y[col]+"px"
});
y[col] += $(this).height();
h = Math.max(h, y[col]);
col += 1;
if (col >= C)
col = 0;
});
$("#posts").css("height", h+"px");
if (first) {
first = false;
setTimeout(real_rsz, 150);
}
}, 150);
};
$K.imagesLoaded(function() {
$(window).on("resize", rsz);
rsz();
});
});
答案 0 :(得分:1)
由于您不需要溢出,只需将图像放在尺寸为1:1.5比例的div中,并将div的overflow属性设置为隐藏。此外,将图像宽度设置为占父div的100%。这样可以防止图像拉伸。
div {
float: left;
width: 100px;
height: 100px;
margin-right: 100px;
}
#clipped {
overflow: hidden;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
img {
position: relative;
width: 100%;
}
<div>
<img src="http://www.publicdomainpictures.net/pictures/140000/velka/watch-vector.jpg">
</div>
<br>
<div id="clipped">
<img src="http://www.publicdomainpictures.net/pictures/140000/velka/watch-vector.jpg">
</div>
答案 1 :(得分:0)
$(document).ready(function() {
$('.story-small img').each(function() {
var maxWidth = 100; // Max width for the image
var maxHeight = 100; // Max height for the image
var ratio = 0; // Used for aspect ratio
var width = $(this).width(); // Current image width
var height = $(this).height(); // Current image height
// Check if the current width is larger than the max
if(width > maxWidth){
ratio = maxWidth / width; // get ratio for scaling image
$(this).css("width", maxWidth); // Set new width
$(this).css("height", height * ratio); // Scale height based on ratio
height = height * ratio; // Reset height to match scaled image
width = width * ratio; // Reset width to match scaled image
}
// Check if current height is larger than max
if(height > maxHeight){
ratio = maxHeight / height; // get ratio for scaling image
$(this).css("height", maxHeight); // Set new height
$(this).css("width", width * ratio); // Scale width based on ratio
width = width * ratio; // Reset width to match scaled image
height = height * ratio; // Reset height to match scaled image
}
});
});
答案 2 :(得分:0)
我通过添加另一个带有单独&#34; r&#34;的数学变量来解决这个问题。代表代码末尾的比率高度。
var w = Math.ceil($("#posts-container").width() / C);
console.log("rsz", r);
$(".entry").css({ "height": (r*1.5)+"px" });
};
$K.imagesLoaded(function() {
$(window).on("resize", rsz);
rsz();
});
});