我只想为支持拖放文件的浏览器在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
checkout modernizr用于HTML5拖放检测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
}