用Javascript为点击事件添加下载函数

add download function to a click event with Javascript

本文关键字:添加 下载 函数 事件 Javascript      更新时间:2023-09-26

我想知道是否有可能在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中不支持下载属性