如何使用javascript预先缓存图像以便快速查看? [英] How do I pre-cache images for quick viewing with javascript?
问题描述
我有一个网页,我希望用户在将鼠标放在图像的某个部分上时看到新图像。我使用了图像映射。
I have a webpage where I want the user to see a new image when they put thier mouse over a certain part of the image. I used an image map.
<img src="pic.jpg" usemap="#picmap" />
<map id="picmap" name="picmap"><area shape="rect" coords ="10,20,30,40"
onMouseOver="mouse_on_write('mouse is on spot')"
onMouseOut="mouse_off('mouse is off spot')"
href="http://www....html" target="_blank" />
</map>
<p id="desc"></p>
在标题中我定义了这些函数:
Where in the header I defined these functions:
<script type="text/javascript">
function mouse_off(txt)
{
document.getElementById("desc").innerHTML=txt;
document.p1.src="pic.jpg";
}
function mouse_on_write(txt)
{
document.getElementById("desc").innerHTML=txt;
document.p1.src="pic2.jpg";
</script>
它有效,但速度很慢。将鼠标放在第二张图像上时,需要几秒钟才能显示;我的临时解决方案是大幅减小图像的大小,因为它们很大(现在它们快速切换为2.5mb,但仍然不是无缝的)。 如何在不降低图像质量的情况下使图像切换更加无缝?
第二个想法我意识到我也可以只显示小尺寸和大尺寸的图像,鼠标悬停时,他们会切换位置;我该怎么做?这会减少滞后吗?
It works, but it is slow. When the mouse is put over the second image it takes some few seconds to appear; my temporary solution was to drastically reduce the size of the images because they were huge (at 2.5mb they switch fast now, but still not seamless). How can I make the image switching more seamless without reduction in picture quality? On second thought I realize that I could also just have both images displayed, at a small and a large scale, and on mouse over they would switch places; How would I do this? Would this reduce lag?
推荐答案
您不需要创建任何页面元素,它们都可以使用JavaScript预加载:
You don't need to create any page elements, it can all be preloaded using JavaScript:
tempImg = new Image()
tempImg.src="pic2.jpg"
编辑:
如果您有很多图像,可以使用穷人的多种图像preloader:
If you have a lot of images, you can use the poor-man's multi-preloader:
preloads = "red.gif,green.gif,blue.gif".split(",")
var tempImg = []
for(var x=0;x<preloads.length;x++) {
tempImg[x] = new Image()
tempImg[x].src = preloads[x]
}
这篇关于如何使用javascript预先缓存图像以便快速查看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!