2007/11/07 09:20
文章作者:Enjoy 转载请注明原文链接。
先是在CSDN查到了这个代码:<img src="http://expert.csdn.net/images/jspd_wdzx_flgg.gif" id=mxh>
<input type=button onclick="a=window.open(document.all.mxh.src);a.document.execCommand('SaveAs')" value="save">
要求在同一个domain(域)
<input type=button onclick="a=window.open(document.all.mxh.src);a.document.execCommand('SaveAs')" value="save">
要求在同一个domain(域)
试了下,是新建一个窗口,显示这张图片,然后另存,最后关掉这个窗口。但在Maxthon下试下,新开的窗口似乎关不掉。
后来,在czxiu发现了这样的代码,有效。
整理下,它是通过将隐藏iframe的地址设置为图片的地址,实现另存的。
实现的代码如下:
先在页面中加入一个隐藏iframe。
<div style="display:none;">
<iframe width="0" height="0" id="genFrm" name="_genFrm" src="about:blank"></iframe>
</div>
<iframe width="0" height="0" id="genFrm" name="_genFrm" src="about:blank"></iframe>
</div>
JS实现函数
function SaveImage(img)
{
var win = $('genFrm').contentWindow;
if (!win || img.tagName != 'IMG') return;
win.location.href = img.src;
setTimeout(function() { win.document.execCommand("SaveAs"); }, 200);
}
{
var win = $('genFrm').contentWindow;
if (!win || img.tagName != 'IMG') return;
win.location.href = img.src;
setTimeout(function() { win.document.execCommand("SaveAs"); }, 200);
}
页面中代码
<img src="/img/title_wait.gif" id="DemoImg" border="0" />
<a href="javascript:void(SaveImage(document.getElementById('DemoImg')))">点击这里下载图片</a>
img的src必须和页面是同一域的,否则会出现权限错误的提示。非同域的图片目前没有找到用JS保存的方法。不过,此功能在Firefox下无效。