用Javascript为点击事件添加下载函数
add download function to a click event with Javascript
我想知道是否有可能在Javascript中添加下载函数到单击事件,例如,当用户单击图像时,它会自动下载。例如,我有一个图像标签<img src="filelocation" id="img"/>
,并希望它被下载点击。(我不能用"download="myfile.png"
。
有没有类似
$('#img').on('click',function(e){
img.download="myfile.png";
});
所有的在线答案建议添加download="..."
到我的标签
谢谢!
可以这样写:
document.getElementById('download').click();
<a id="download" href="https://assets.entrepreneur.com/content/16x9/822/20150721193719-solshero3.jpeg" download hidden></a>
Play with it: here
但是如果你真的不能使用download属性:Play this then.
祝你好运! !
你可以在点击图片时创建一个anchor
元素,并使用.click()
来触发点击该anchor
,即使它没有附加到你的页面。
如果这仍然违反要求,那么您可能必须通过服务器端工作来实现它。
参见更改javascript下载名称
window.onload = function() {
// Fake image for testment
var canvas = document.createElement('canvas');
canvas.width = 300;
canvas.height = 200;
var ctx = canvas.getContext('2d');
ctx.fillStyle = 'black';
ctx.fillRect(0, 0, 200, 100);
ctx.fillStyle = 'cyan';
ctx.fillText('test', 50, 50);
var makeImageDownloadable = function(image, name) {
image.addEventListener('click', function() {
var a = document.createElement('a');
a.href = image.src;
// may need to check the datatype, or just write image to another tmp canvas first.
a.download = name + '.png';
a.click();
});
};
var image = new Image();
image.onload = function() {
document.querySelector('#holder').appendChild(image);
makeImageDownloadable(image, 'testimage');
};
image.src = canvas.toDataURL('image/png');
};
<div id="holder"></div>
您可以使用HTML5
下载属性
<a href="http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg" download="my_download.png"><img src="http://www.hdwallpapersimages.com/wp-content/uploads/2014/01/Winter-Tiger-Wild-Cat-Images.jpg">
</a>
我不确定浏览器的兼容性,更好的解决方案是包括服务器端脚本。
JSFiddle: http://jsfiddle.net/k2rear94/
如果你想让它是动态的,试试这个
$("SomeElement").onclick = function(){
$("<a id='tmp' href='link' download ></a>).appendTo("body");
$("#tmp").click();
$("#tmp").remove();
}
但是请记住,IE中不支持下载属性
相关文章:
- 剑道UI下载列表:如何动态添加新元素
- 添加一个javascript函数来下载elfinder上的事件
- 为文件添加下载选项
- 将打印和下载受保护的 PDF 查看器添加到网站
- 如何添加指向 Fancybox 的链接以下载图像的高分辨率版本
- 一键下载链接并在浏览器操作中添加书签
- JS下载添加文本的图像
- ASP.NET通过EventHandler中添加的客户端javascript下载文件
- 在“下载文件”对话框中添加一个选项
- 自动为PDF下载添加唯一编号
- 如何跳过第一行并添加标题以下载csv文件
- Datatables csv下载将自定义列添加到文件中
- 将下载的.js文件添加到Netbeans中现有的Project中
- 好的上传器,习惯的方式添加下载按钮,每个文件上传
- 用Javascript为点击事件添加下载函数
- 在一个库被添加/下载并以承诺的方式执行后,是DOM中的元素
- 添加下载链接的时间限制
- 在播放器播放曲目上添加下载按钮
- 如何向项目中的用户添加下载链接
- 添加一行到HTML表&它添加成功,但我想导入该表的数据到excel表格如何添加下载按钮