我已经在 DOM 中加载了一个由变量 img
引用的图像。
我想将元素的背景图像设置为 DOM 中加载的图像。
如果我只是简单地执行“background-image:url('"+img.src+"')”,问题是这取决于浏览器是否缓存图像(对于明确不存储缓存或缓存的用户代理)最大尺寸 0,基本上,拧紧)
如果浏览器没有缓存图像,则会请求一个新图像(这显然是我试图阻止的,因为图像已经在 dom 中,重新请求它是不必要的)
我们如何设置 DOM 中已加载图像的元素的背景图像?
简单的测试脚本来证明图像会被重新请求,(使用可以清除缓存的浏览器来测试)http://qweop.com/test/cache.php :
<!doctype html><html>
<head></head>
<body onload="load();" >
Step 0. Open your network inspector.<br>
Step 1. Wait for image to finish loading.<br>
Step 2. Clear your browser's cache (do not refresh this page);<br>
<button disabled="disabled" id="button" onclick="
document.getElementById('div').style.backgroundImage='url('+document.getElementById('img').src+')';
">Step 3. After Cache is cleared, click</button>
<br>
<img id="img" width="500" height="500" src="http://upload.wikimedia.org/wikipedia/commons/archive/4/4e/20090223155149!Pleiades_large.jpg" onload="
document.getElementById('button').disabled='';"
/>
<div id="div" style="display:inline-block;width:500px;height:500px;background-color:yellow;"></div>
</body>
</html>
最佳答案
您可以将图像下载为 img
实例的 .src
的 Base64 字符串。将 img.src
复制到 background-image:url
将复制图像的此数据字符串,而不是检查缓存或下载它。例如:
<img src = "data:image/gif;base64, SOMEBASE64STRING" />
您可以获得图像的 Base64 版本 here ,用 PHP 生成它,如 here ,或使用 canvas
元素从图像生成 Base64 字符串,如所述 here .
关于javascript - 我们如何设置 DOM 中已加载图像的元素的背景图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6893007/