Detecting HTML5 Drag And Drop support in javascrip

2019-01-17 16:08发布

问题:

I'm trying to detect the HTML5 Drag And Drop support in JavaScript. Modernizr seems to not handle this test case.

回答1:

You can do this:

if('draggable' in document.createElement('span')) {
  alert("Drag support detected");
}

You can see a quick demo test using the above check here.

Also, there's a nice feature detection (not browser detection, yay!) list that's fairly well maintained here in case you're looking for other HTML5 features as well.



回答2:

Detecting "draggable' in document.createElement('span') seems like a good idea, but in practice it doesn't work.

iOS claims that draggable is in the element but doesn't allow drag and drop. (Reference: Safari Web Content Guide: Handling Events)

IE9 claims that draggable is NOT in the element, but does allow drag and drop. (Reference: my testing HTML5 drag and drop in IE.)

Modernizr is a better choice because it doesn't confuse IE. However, it states that HTML5 drag and drop is available on iOS.

Here's how I detect HTML5 drag and drop:

var iOS = !!navigator.userAgent.match('iPhone OS') || !!navigator.userAgent.match('iPad');
if (Modernizr.draganddrop && !iOS) {
    HTML5 drag and drop solution
} else if (Modernizr.draganddrop && iOS) {
    iOS drag and drop solution 
} else {
    non-HTML5 drag and drop solution
}


回答3:

This is how it's implemented in Modernizr

function() {
    var div = document.createElement('div');
    return ('draggable' in div) || ('ondragstart' in div && 'ondrop' in div);
}


回答4:

Check if "dragstart" and "drop" are supported, using the "isEventSupported" method in Modernizr. See How to detect browser support File API drag n drop.