鍍金池/ 問(wèn)答/HTML/ 火狐瀏覽器的a標(biāo)簽無(wú)法實(shí)現(xiàn)下載

火狐瀏覽器的a標(biāo)簽無(wú)法實(shí)現(xiàn)下載

問(wèn)題描述

想通過(guò)a標(biāo)簽實(shí)現(xiàn)canvas的下載,相同的代碼在谷歌瀏覽器下可行,在火狐下卻無(wú)法實(shí)現(xiàn)

相關(guān)代碼

// 請(qǐng)把代碼文本粘貼到下方(請(qǐng)勿用圖片代替代碼)
var mycanvas = $("#export11").find("canvas")[0];

  var image = mycanvas.toDataURL("image/jpeg");
  var $a = document.createElement('a');
  $a.setAttribute("href", image);
  $a.setAttribute("download", this.state.nowDate + "多能點(diǎn)號(hào)圖");
  $a.click();

回答
編輯回答
忠妾

$a.click() 改成 $a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));

    var mycanvas = $("#export11").find("canvas")[0];
    var image = mycanvas.toDataURL("image/jpeg");

    var $a = document.createElement('a');
    $a.setAttribute("href", image);
    $a.setAttribute("download",  "多能點(diǎn)號(hào)圖");
    $a.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));

親證可用

2017年4月18日 15:43
編輯回答
影魅

最后增加一行

    window.URL.revokeObjectURL(image);

你也可以參考我寫(xiě)的:https://github.com/azl3979858...

2017年11月14日 20:06
編輯回答
不討囍

模擬點(diǎn)擊出現(xiàn)的問(wèn)題,在火狐中直接$a.click()是沒(méi)有效果的,有兩種方式可以實(shí)現(xiàn)。
方法一:

var image = mycanvas.toDataURL("image/jpeg");
var $a = document.createElement('a');
$a.setAttribute("href", image);
$a.setAttribute("download", this.state.nowDate + "多能點(diǎn)號(hào)圖.jpg");//需要加上后綴名
document.body.appendChild($a);
$a.click();
document.body.removeChild($a);

方法二:

var image = mycanvas.toDataURL("image/jpeg");
var $a = document.createElement('a');
$a.setAttribute("href", image);
$a.setAttribute("download", this.state.nowDate + "多能點(diǎn)號(hào)圖.jpg");//需要加上后綴名
const evt = document.createEvent('Event');
evt.initEvent("click", true, true);
$a.dispatchEvent(evt);
2017年10月1日 08:51
編輯回答
舊時(shí)光

火狐的話(huà),js創(chuàng)建a標(biāo)簽實(shí)現(xiàn)自動(dòng)下載,需要?jiǎng)?chuàng)建a標(biāo)簽添加到body上,然后執(zhí)行click操作,下載完之后再移除你創(chuàng)建的標(biāo)簽就好。

2018年3月1日 17:17