63

现在我有一个canvas,我想将它保存为 PNG。我可以使用所有那些花哨的复杂文件系统 API 来做到这一点,但我真的不喜欢它们。

我知道上面是否有带有download属性的链接:

<a href="img.png" download="output.png">Download</a>

如果用户单击它,它将下载文件。因此我想出了这个:

$("<a>")
    .attr("href", "img.png")
    .attr("download", "output.png")
    .appendTo("body")
    .click()
    .remove();

演示:http: //jsfiddle.net/DerekL/Wx7wn/

但是,它似乎不起作用。它是否必须由用户操作触发?否则为什么它不起作用?

4

2 回答 2

84

正如@Ian解释的那样,问题在于jQueryclick()与原生的不一样。

因此,考虑使用 vanilla-js 而不是 jQuery:

var a = document.createElement('a');
a.href = "img.png";
a.download = "output.png";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);

演示

于 2015-03-05T23:54:56.957 回答
82

The problem is that jQuery doesn't trigger the native click event for <a> elements so that navigation doesn't happen (the normal behavior of an <a>), so you need to do that manually. For almost all other scenarios, the native DOM event is triggered (at least attempted to - it's in a try/catch).

To trigger it manually, try:

var a = $("<a>")
    .attr("href", "http://i.stack.imgur.com/L8rHf.png")
    .attr("download", "img.png")
    .appendTo("body");

a[0].click();

a.remove();

DEMO: http://jsfiddle.net/HTggQ/

Relevant line in current jQuery source: https://github.com/jquery/jquery/blob/1.11.1/src/event.js#L332

if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
        jQuery.acceptData( elem ) ) {
于 2013-06-26T04:43:59.753 回答