Мне нужно изменить размер нескольких изображений.Изменение размера нескольких изображений с помощью javascript
Это HTML:
<img id="thumbnailId" src='http://thumbs1.ebaystatic.com/m/mPlrV_wS_b1vK9avUQ22r9w/140.jpg' class="img-responsive galleryproductimg" style="border: 0px solid blue; margin-top:10px;" />
<img id="thumbnailId" src='http://thumbs1.ebaystatic.com/m/mIeHLNVqUI1opFM0NmZvH_A/140.jpg' class="img-responsive galleryproductimg" style="border: 0px solid blue; margin-top:10px;" />
И мой код JavaScript:
$(document).ready(function() {
console.log("ready to go");
var imgs = getElementsById("thumbnailId");
for (var i = 0; i < imgs.length; i++) {
var img = imgs[i];
img.onload = function() {
console.log("image is loaded");
}
resizeImage(img);
}
});
функции, вызываемые из этого:
function getElementsById(elementID) {
var elementCollection = new Array();
var allElements = document.getElementsByTagName("*");
for(i = 0; i < allElements.length; i++) {
if(allElements[i].id == elementID)
elementCollection.push(allElements[i]);
}
return elementCollection;
}
И
function resizeImage(img) {
console.log("width, height, src " + img.width + ", " + img.height + ", " + img.src);
console.log("loaded? " + img.complete);
var width = img.width;
var height = img.height;
var constant = 100;
var ratio = width/height;
console.log("ratio " + ratio);
if(width > constant || height > constant) {
var newWidth = constant;
var newHeight = constant*ratio;
if(width > height) {
newWidth = constant;
newHeight = constant*ratio;
} else {
newWidth = constant*ratio;
newHeight = constant;
}
console.log("newWidth, newHeight " + newWidth + ", " + newHeight);
//img.width = newWidth;
//img.height = newHeight;
img.style.width = newWidth + "px;";
img.style.height = newHeight + + "px;";
console.log("img from url AFTER " + img.width + ", " + img.height);
}
console.log("==========================");
}
Код кажется правильным и работает для одного изображения. Но не для нескольких изображений. Выход, который я получаю, таков:
ready to go
resizeImages called
width, height, src 84, 110, http://thumbs1.ebaystatic.com/m/mPlrV_wS_b1vK9avUQ22r9w/140.jpg
loaded? true
ratio 0.7636363636363637
newWidth, newHeight 76.36363636363637, 100
img from url AFTER 84, 110
==========================
width, height, src 86, 110, http://thumbs1.ebaystatic.com/m/mIeHLNVqUI1opFM0NmZvH_A/140.jpg
loaded? true
ratio 0.7818181818181819
newWidth, newHeight 78.18181818181819, 100
img from url AFTER 86, 110
==========================
2 image is loaded
Так что в принципе я даже не получаю правильные размеры изображения с самого начала. По какой-то причине ширина всегда 110. Есть идеи, что здесь происходит?
не может получить размеры изображения до загрузки изображения – charlietfl
resizeImage (img); вызов за пределами цикла for – YouYou
Я положил его в цикле и внутри функции.onLoad. Тот же результат. – Eddy