javascript 如何检测对 HTML5“下载”属性的支持?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12112844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 15:20:56  来源:igfitidea点击:

How to detect support for the HTML5 "download" attribute?

javascripthtml

提问by Andrei Oniga

One of the new features implemented in HTML5 is the downloadattribute for anchor tags. The benefit of this attribute is that it gives users the means to download content created within a client application, such as an image (converted from a canvas, for instance).

HTML5 中实现的新功能之一是download锚标记的属性。此属性的好处在于,它为用户提供了下载在客户端应用程序中创建的内容的方法,例如图像(例如从画布转换而来)。

Currently, support for this feature is very poor, so I'd like to know how can I detect support for this feature in a browser.

目前,对这个功能的支持很差,所以我想知道如何在浏览器中检测对这个功能的支持。

回答by McGarnagle

Use the Modernizrapproach: create the element, and check if the attribute is defined:

使用Modernizr方法:创建元素,并检查属性是否已定义:

var a = document.createElement('a');
if (typeof a.download != "undefined") {
    alert('has support');
}

回答by John

A single-line ifcondition to keep things simplified:

if使事情变得简单的单行条件:

if (document.createElement('a').download==undefined && e.target.hasAttribute('download'))
{
 e.preventDefault();
 console.log('Error: this is a download link, please right-click to save the file.');
}

Support for the downloadattribute is spotty (Chrome 14+, Firefox 20+, IE13+, Safari 10+ and no support in (real) Opera. The script above will not interfere with supported browsers.

对该download属性的支持参差不齐(Chrome 14+、Firefox 20+、IE13+、Safari 10+,在(真实)Opera 中不支持。上述脚本不会干扰支持的浏览器。