我想在一个div上添加背景,但仅适用于支持文件拖放的浏览器
我不想使用modernizr,只需一行脚本即可
我想在一个div上添加背景,但仅适用于支持文件拖放的浏览器
我不想使用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;
};
如果您不想处理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
return 'draggable' in document.createElement('span') && typeof(window.FileReader) != 'undefined';
检查使用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
}
is
函数的定义。 - Emmerman