在我的Tumblr博客上,我正在尝试使用jQuery来选择具有特定比率的照片条目(imgs),并以某种方式调整它们的大小。
具体来说:如果图像的宽度大于250px,请调整其大小,使其高度为250px,宽度为“auto”。如果图像的高度大于250px,请调整其宽度,使其宽度为250px,高度为“auto”。最后,如果图像是完美的正方形,请将其调整为250px至250px。
这是我目前正在使用的。如果它是奇怪的编码,请原谅我,老实说我只是摆弄它,直到我得到一些理想的结果......
<script>
$(document).ready(function() {
$('.photo_post img').each(function() {
var maxWidth = 250; // Max width for the image
var maxHeight = 250; // 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(height > maxHeight){
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
}
});
});
</script>
我的问题是它在所有照片上都无法正常工作 我对jQuery并不是很熟悉,所以我们非常感谢有意识和详细的解答。
答案 0 :(得分:0)
您需要检查图像是纵向还是横向,然后根据该尺寸调整尺寸。
更新了JS:
$(document).ready(function() {
$('.photo_post img').each(function() {
var maxWidth = 250; // Max width for the image
var maxHeight = 250; // 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
// Portrait
if (height > width) {
// Check if the current height is larger than the 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
}
}
// Landscape
else {
// 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
}
}
});
});