[英]Select, then resize images that have a certain ratio with jQuery
在我的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
}
}
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.