簡體   English   中英

使用Javascript將下載功能添加到click事件

[英]add download function to a click event with Javascript

我想知道是否有可能僅使用Javascript將下載功能添加到click事件中,例如,當用戶單擊圖像時,它會自動下載。 例如,我有一個圖像標簽<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> 

玩: 這里

但是,如果您真的沒有下載屬性,請執行以下操作

祝好運!!

您可以在單擊圖像時創建anchor元素,並使用.click()觸發對該anchor的單擊,即使該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不支持下載屬性。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM