我对网页设计和与之相关的编程非常陌生。我正在使用 JavaScript 制作一个简单的画廊,我知道使用 jQuery 非常容易。但是我不被允许使用它(作业)。
这是问题所在的代码:
var img = new Array(); //declared globally, accessed by other functions
function displayImage(){
var img_num = document.getElementById('img_num').getAttribute("value");
for(j=0;j<img_num;j++)
img.push(document.getElementById('h'+j).getAttribute("value"));
var list_width = 0;
for(var i=0;i<img_num;i++)
{
document.getElementById('list_holder').innerHTML += "<img src='" +img[i]+ "'onclick=\"show(this.id);\" height = \"70%;\"id='"+i+"'/>";
list_width += document.getElementById(i).offsetWidth + 15;
}
document.getElementById('list_holder').style.width = list_width+"px";
return false;
}
ID为h0,h1,h2...等的元素是隐藏输入类型,包含图像的路径,ID为0,1,2..是标签。
我在 JS 中使用它们将路径存储在数组中 img
使用img.push
。然后我使用数组中的值来创建那么多 <img>
标签(指定高度,宽度由宽高比决定。现在我需要计算这些 div
的父 img
('list_width') 的总宽度标签,所以我想到使用 list_width+=document.getElementById(i).offsetWidth
。
但是发生的情况是,当我第一次打开页面时,实际宽度没有被返回。它返回 4
,这基本上是我计算的标签的最小宽度。仅在刷新页面时它才能按预期工作。我知道我可以通过在加载页面后刷新一次页面来使用解决方法,但我想知道是否有任何“首选”或“专业”方法可以做到这一点。
提前致谢。
最佳答案
您必须等待图像加载。您是 Javascript 新手,但您已经不得不面对异步编程。让我们在评论中看到这一点:
var img = []; // faster to type, use this syntax if you
// don't define an initial length
function displayImage() {
// The attribute value defines the initial value of the input element, and
// it may differ from the actual value. So use the value property, not the
// attribute.
var img_num = document.getElementById('img_num').value;
for(var j=0; j<img_num; j++) // Watch out, without var j is global!
img.push(document.getElementById('h'+j).value);
var list_width = 0,
// We're referincing this element a lot, better store it
lholder = document.getElementById('list_holder'),
htmllist = []; // See the trick
for(var i=0; i<img_num; i++)
htmllist.push("<img src='" +img[i]
+ "'onclick=\"show(this.id);\" height = \"70%;\"id='"+i+"'/>");
// Every time you set innerHTML, using = or +=, the browser has to parse
// the code and rebuild the content, and it's an expensive task. Set this
// property only once you already computed all the HTML you need.
lholder.innerHTML = htmllist.join("");
var loaded = 0;
for(var i=0; i<img_num; i++)
// You don't know when the images will be loaded. But when an image is
// loaded, it triggers the load event that you can listen setting the
// onload property (or, in a more modern way, setting an event listener
// with addEventListener or attachEvent in older IE). Count the images
// that are loaded, and when they're all loaded do your stuff.
lholder.childNodes[i].onload = function() {
if (++loaded < img_num) return;
for(var i=0; i<img_num; i++)
list_width += lholder.childNodes[i].offsetWidth;
lholder.style.width = list_width + "px";
};
return false;
}
关于javascript - JavaScript 有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16129725/