我下面的JavaScript代码调整产品图像大小并将它们放在一个盒子中。这个代码在调用onload时工作得很好,但我有一个返回20个产品的ajax调用。当我Ajax调用后在onload后调用这个函数,它会调整任何图像是165x165px方,不管它的proportions.Here是JavaScript:Javascript图像尺寸和定位
function resizeProductImages(optimumHeight, optimumWidth, className)
{
images = document.getElementsByTagName('img');
for(var i=0;i<images.length;i++)
{
if(images[i].className == className)
{
images[i].removeAttribute("width");
images[i].removeAttribute("height");
images[i].style.left = "0px";
images[i].style.top = "0px";
h = images[i].height;
w = images[i].width;
if(h > w)
{
images[i].height = optimumHeight;
images[i].style.position = "absolute";
images[i].style.display = "block";
var scaledown = optimumHeight/h;
var realWidth = scaledown * w;
var realHeight = optimumWidth - realWidth;
var gaps = realHeight/2;
images[i].style.left = gaps+"px";
}
else if(w > h)
{
images[i].width = optimumWidth;
images[i].style.position = "absolute";
images[i].style.display = "block";
var scaledown = optimumWidth/w;
var realHeight = scaledown * h;
var realWidth = optimumHeight - realHeight;
var gaps = realWidth/2;
images[i].style.top = gaps+"px";
}
else if(h == w)
{
images[i].height = optimumHeight;
images[i].width = optimumWidth;
}
}
}
}
function resizeProductCategoryImages()
{
resizeProductImages(165, 165, 'roller');
}
任何想法,为什么?
编辑
我从评论的意见和更换DOM具有可变调用并发布上述新代码。
进一步编辑
这是因为图像还未当函数调用,因此图像具有0尺寸,0有什么办法让这个功能直到所有的图像加载被加载?
我认为你应该使用变量更多,它们很棒 – Esailija
附注:DOM调用(例如'document.getElementsByTagName')很贵。将结果存储在变量中会有所帮助。 –
叫我疯了,但它看起来像它调整到165,因为你告诉它:'resizeProductImages(165,165,'roller');' –