一些 javascript 问题:奇怪的时间依赖性和图像第一次未加载
我正在尝试创建一个脚本来创建包含图像和一些文本的覆盖层,但我
首先遇到了一些问题:第一次单击时覆盖层中的图像不会出现,但在后续打开时会出现。
第二:scrollTo 函数只有在超时时才起作用,否则它似乎什么也不做。
如果有人能阐明这一点或我犯的任何其他错误,我将不胜感激。
javascript:
var scrollY;
var i_w;
var i_h;
function showOverlay(filepath,num){
scrollY = document.body.scrollTop || document.documentElement.scrollTop;
hideOverlay();
document.getElementById("num").innerHTML ="image #: " + num + " click image to close";
var preload = new Image();
preload.src = filepath;
i_w = preload.width;
i_h = preload.height;
document.getElementById("blowup").width = i_w;
document.getElementById("blowup").height = i_h;
document.getElementById("blowup").src = filepath;
document.getElementById("overlay").style.display = "inline";
setTimeout("window.scrollTo(0,scrollY)",1);
setOverlayBounds(); //a function to orient the overlay div.
}
html:
<div id="overlay">
<center>
<img id="blowup" src="#" onClick="javascript:hideOverlay()">
<br>
<p id="num"></p>
<br>
</center>
</div>
css:
#overlay
{
display:none;
position:absolute;
background-color:#999;
border:medium;
border-color:#0F0
}
I'm trying to create a script for creating an overlay containing an image and some text, but i've run into some problems
1st: the image in the overlay doesn't appear when first clicked, but does on subsequent openings.
2nd: the scrollTo function only works if put in a timeout, otherwise it appears to do nothing.
If anyone could shed any light on this, or any other mistakes i've made, it would be much appreciated.
javascript:
var scrollY;
var i_w;
var i_h;
function showOverlay(filepath,num){
scrollY = document.body.scrollTop || document.documentElement.scrollTop;
hideOverlay();
document.getElementById("num").innerHTML ="image #: " + num + " click image to close";
var preload = new Image();
preload.src = filepath;
i_w = preload.width;
i_h = preload.height;
document.getElementById("blowup").width = i_w;
document.getElementById("blowup").height = i_h;
document.getElementById("blowup").src = filepath;
document.getElementById("overlay").style.display = "inline";
setTimeout("window.scrollTo(0,scrollY)",1);
setOverlayBounds(); //a function to orient the overlay div.
}
html:
<div id="overlay">
<center>
<img id="blowup" src="#" onClick="javascript:hideOverlay()">
<br>
<p id="num"></p>
<br>
</center>
</div>
css:
#overlay
{
display:none;
position:absolute;
background-color:#999;
border:medium;
border-color:#0F0
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用图像的加载事件来确保它在执行代码之前完成加载。另外,您不应将字符串与 setTimeout 结合使用。最好直接传递函数:
这至少应该解决您的第一个问题。
You should use the load event for the image to make sure, it finished loading before you execute your code. Also, you shouldn't use strings in connection with setTimeout. It's better to pass the function directly:
This should at least fix your first issue.