如何在JavaScript中克隆图像 [英] How can i clone an image in javascript
问题描述
我试图在javascript中克隆图片,但不加载新的图片。
通常,新浏览器会加载图片一次,有几种使用方式那个图像了。
问题是,当我在IE 6测试它的图像将从服务器请求一个新的图像。
任何人如何在旧版浏览器中如何做到这一点的一些信息?
3种不起作用的方法:
I'm trying to clone an image in javascript, bud without loading a new one.
Normally new browsers will load an image once and there are several ways to use that image again.
The problem is that when I test it in IE 6 the image will request a new image from the server.
Anyone how has some info on how to do this in older browsers?
3 methods that not work:
<html>
<head>
<title>My Image Cloning</title>
<script type="text/javascript">
sourceImage = new Image();
sourceImage.src = "myImage.png";
function cloneImageA () {
imageA = new Image();
imageA.src = sourceImage.src;
document.getElementById("content").appendChild(imageA);
}
function cloneImageB () {
imageB = sourceImage.cloneNode(true);
document.getElementById("content").appendChild(imageB);
}
function cloneImageC()
{
var HTML = '<img src="' + sourceImage.src + '" alt="" />';
document.getElementById("content").innerHTML += HTML;
}
</script>
</head>
<body>
<div id="controle">
<button onclick="cloneImageA();">Clone method A</button>
<button onclick="cloneImageB();">Clone method B</button>
<button onclick="cloneImageC();">Clone method C</button>
</div>
<div id="content">
Images:<br>
</div>
</body>
在映像目录中添加了带有简单的.htaccess文件的缓存标头服务器端:
/img/.htaccess
Added cache-headers server-side with a simple .htaccess file in the directory of the image(s):
/img/.htaccess
Header unset Pragma
Header set Cache-Control "public, max-age=3600, must-revalidate"
如果设置了cache-headers,所有上述javascript方法都将使用加载的图像。 / p>
All of the above javascript method's will use the image loaded if the cache-headers are set.
推荐答案
Afaik的默认浏览器行为是缓存图像。所以这样的东西应该按照你想要的方式工作:
Afaik the default browser behavior is to cache images. So something like this should work the way you want:
var sourceImage = document.createElement('img'),
imgContainer = document.getElementById("content");
sourceImage.src = "[some img url]";
imgContainer.appendChild(sourceImage);
function cloneImg(){
imgContainer.appendChild(sourceImage.cloneNode(true));
}
这是所有的sop,所以它应该运行在IE6 t有它,所以不能测试)。
查看操作
It's all pretty sop, so it should run in IE6 too (I don't have it, so can't test that). See it in action
此外,您可能希望检查IE6浏览器的缓存设置。我记得从IE< 8没有这么好的旧日子,我有时恢复到设置缓存刷新每次你加载页面(或像这样)。
Furthermore, you may want to check the cache setting of your IE6 browser. I remember from the not so good old days with IE<8 that I sometimes reverted to setting the cache to refresh "every time you load the page" (or someting like that).
这篇关于如何在JavaScript中克隆图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!