我喜欢只为支持拖放文件的浏览器在 div 上添加背景
我不喜欢使用modernizr,只是一个单行脚本
为什么不直接从 Modernizr 复制所需的部分?
var isEventSupported = (function() {
var TAGNAMES = {
'select': 'input', 'change': 'input',
'submit': 'form', 'reset': 'form',
'error': 'img', 'load': 'img', 'abort': 'img'
};
function isEventSupported( eventName, element ) {
element = element || document.createElement(TAGNAMES[eventName] || 'div');
eventName = 'on' + eventName;
// When using `setAttribute`, IE skips "unload", WebKit skips "unload" and "resize", whereas `in` "catches" those
var isSupported = eventName in element;
if ( !isSupported ) {
// If it has no `setAttribute` (i.e. doesn't implement Node interface), try generic element
if ( !element.setAttribute ) {
element = document.createElement('div');
}
if ( element.setAttribute && element.removeAttribute ) {
element.setAttribute(eventName, '');
isSupported = typeof element[eventName] == 'function';
// If property was created, "remove it" (by setting value to `undefined`)
if ( typeof element[eventName] != 'undefined' ) {
element[eventName] = undefined;
}
element.removeAttribute(eventName);
}
}
element = null;
return isSupported;
}
return isEventSupported;
})();
用法:
if (isEventSupported('dragstart') && isEventSupported('drop')) {
...
}
对于文件 API:
var isFileAPIEnabled = function() {
return !!window.FileReader;
};
您可以使用:
return 'draggable' in document.createElement('span') && typeof(window.FileReader) != 'undefined';
如果您根本不想处理 Modernizr,您可以复制它对拖放检测的作用:
var supportsDragAndDrop = function() {
var div = document.createElement('div');
return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
}
从 Modernizr GitHub 存储库获得它:
https://github.com/Modernizr/Modernizr/blob/master/feature-detects/draganddrop.js
查看用于 HTML5 拖放检测的 modernizr 源代码 技术https://github.com/Modernizr/Modernizr/blob/master/feature-detects/draganddrop.js
除了这似乎错误地将 iOS 检测为支持拖放
不知道为什么每个人都需要创建一个新元素来检查这一点。我认为只检查 body 元素是否支持拖动事件以及浏览器是否支持 File API 就足够了
supportsDragAndDrop(){
body = document.body
return ("draggable" in body || ("ondragstart" in body && "ondrop" in body))
&& window.FormData && window.FileReader
}