我在这里遇到了一些问题。我一直在试图用JavaScript做一个图片库,但是我遇到了一些问题。当第一张图片加载时,我可以调整图片的大小,但只要加载另一张图片,就不会调整大小!由于用户将能够上传很多不同大小的图片,我真的需要让它工作。将动态图像调整为不能运行一次以上
我检查了准备使用的图片库等,没有什么是做我需要做的。
这里是我的javascript:
function changeCurrentImage(conteneur)
{
var img = conteneur.getElementsByTagName("img");
var imgUrl = img[0].src;
var imgFirstPart = imgUrl.substring(0, imgUrl.lastIndexOf('.') - 9);
var imgLastPart = imgUrl.substring(imgUrl.lastIndexOf('.'));
var currentImg = document.getElementById('currentImage');
currentImg.src = imgFirstPart + "borne" + imgLastPart;
resize(document.getElementById('currentImage'), 375, 655);
}
function resize(img, maxh, maxw) {
var ratio = maxh/maxw;
if (img.height/img.width > ratio){
// height is the problem
if (img.height > maxh){
img.width = Math.round(img.width*(maxh/img.height));
img.height = maxh;
}
} else {
// width is the problem
if (img.width > maxw){
img.height = Math.round(img.height*(maxw/img.width));
img.width = maxw;
}
}
};
这里是HTML(使用ASP.Net中继器):
<asp:Repeater ID="rptImages" runat="server">
<HeaderTemplate>
</HeaderTemplate>
<ItemTemplate>
<a href="#">
<div id="thumbnailImageContainer1" onclick="changeCurrentImage(this)">
<div id="thumbnailImageContainer2">
<img id="thumbnailImage" src="<%# SiteUrl + Eval("ImageThumbnailPath")%>?rn=<%=Random()%>" alt="Photo" onload="resize(this, 60, 105)" />
</div>
</div>
</a>
</ItemTemplate>
<FooterTemplate>
</FooterTemplate>
</asp:Repeater>
难道你不能在服务器端做到这一点?这将是更好的方式,因为用户可能被迫下载一个稍后调整大小的大文件。 – 2010-11-12 22:18:37
在你的代码中,你在哪里设置“currentImage”作为id?也许我只是想念它,但它并没有出现在你的changeCurrentImage(没有setAttribute('id','currentImage')),并且你的ASP也不存在。然而,这是实际“调整大小”的图像。 – 2010-11-12 22:24:22
@Jason:很好,但永远不会使用'setAttribute'来设置像'id'和'class'这样的属性。 IE会对此窒息。只需使用本地DOM属性,如'element.id'。 – 2010-11-12 22:41:23