如何检测浏览器支持File API drag n drop

问题描述 投票:4回答:6

我只想为支持拖放文件的浏览器在div上添加背景

尽管我不喜欢使用modernizr,只是一个脚本

javascript drag-and-drop fileapi
6个回答
8
投票

为什么不只是从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;
};

0
投票

您可以使用:

return 'draggable' in document.createElement('span') && typeof(window.FileReader) != 'undefined';


0
投票

如果您根本不想处理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


0
投票

checkout modernizr用于HTML5拖放检测https://github.com/Modernizr/Modernizr/blob/master/feature-detects/draganddrop.js]的源代码技术>


0
投票

除非这似乎错误地将iOS检测为支持拖放操作


0
投票

不知道为什么每个人都需要创建一个新元素来进行检查。我认为仅检查一下body元素是否支持拖动事件以及浏览器是否支持File API就足够了。

supportsDragAndDrop(){
   body = document.body
   return ("draggable" in body || ("ondragstart" in body && "ondrop" in body)) 
        && window.FormData && window.FileReader
}
© www.soinside.com 2019 - 2024. All rights reserved.