在我的Tumblr博客上,我试图使用jQuery选择具有特定比例的照片条目(img),并以某些方式调整它们的大小。
具体来说:如果图像的宽度大于250px,请调整其大小,以使高度为250px,宽度为“自动”。如果图像的高度大于250px,请调整其大小,以使宽度为250px,高度为“自动”。最后,如果图片是完美的正方形,请将其大小调整为250px x 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并不是很熟悉,所以深思熟虑和详尽的答案是值得的。
最佳答案
您需要检查图像是纵向还是横向,然后根据该图像调整尺寸。
更新的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
}
}
});
});