【发布时间】:2011-05-10 04:44:07
【问题描述】:
我已经解决了居中和调整大小的问题,但我仍然无法让 onLoad 正常工作。有人有想法么?我认为onLoad 应该在触发代码之前等待图像完全加载。因为这是现在,它为下一个 img 调整 img 的大小,并在加载之前将其淡入,因此前一个图像再次淡入。一旦节目运行一次,它就可以完美运行,所以显然它不会在触发imageLoad()之前等待图像完全加载。
<div id="slideShow">
<div id="slideShowImg" style="display:none; margin-right:auto; margin-left:auto;">
</div>
<div id="slideShowThumbs">
</div>
<script type="text/javascript">
loadXMLDoc('http://www.thehoppr.com/hopspots/82/82.xml', function() {
var slideShow = document.getElementById('slideShow');
var items = [];
var nl = xmlhttp.responseXML.getElementsByTagName('image');
var i = 0;
var t;
var slideShowImg = document.getElementById('slideShowImg');
var slideShow = document.getElementById('slideShow');
var maxHeight = 300;
var maxWidth = 800;
var imgNode = new Image();
function image() {
var nli = nl.item(i);
var src = nli.getAttribute('src').toString();
var width = parseInt(nli.getAttribute('width').toString());
var height = parseInt(nli.getAttribute('height').toString());
imgNode.onLoad = imageLoad();
imgNode.src = src;
imgNode.height = height;
imgNode.width = width;
imgNode.setAttribute("style", "margin-right:auto; margin-left:auto; display:block;");
var ratio = maxHeight / maxWidth;
if (imgNode.height / imgNode.width > ratio) {
// height is the problem
if (imgNode.height > maxHeight) {
imgNode.width = Math.round(imgNode.width * (maxHeight / imgNode.height));
imgNode.height = maxHeight;
}
} else {
// width is the problem
if (imgNode.width > maxHeight) {
imgNode.height = Math.round(imgNode.height * (maxWidth / imgNode.width));
imgNode.width = maxWidth;
}
}
}
function imageLoad() {
slideShowImg.appendChild(imgNode);
Effect.Appear('slideShowImg', {
duration: 1
});
t = setTimeout(nextImage, 7000);
}
function nextImage() {
slideShowImg.setAttribute("style", "display:none");
if (i < nl.length - 1) {
i++;
image();
} else {
i = 0;
image();
}
}
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//XML Loaded, create the slideshow
alert(xmlhttp.responseText);
image();
}
});
</script>
【问题讨论】:
-
有趣的是,它似乎确实可以在 Chrome 中运行,但不能在 IE 或 Firefox 中运行。显然脚本在分配 onLoad 之前就从缓存中提取了?在显示另一个图像时预加载图像可能是我最好的选择。如果有人可以为我提供一些可能加快速度的示例代码,我将不胜感激,我对 Javascript 还很陌生。不过已经很晚了,我要去睡觉了。
标签: javascript image slideshow