I've implemented HTML5 drag and drop on DIVs. It works great in all browsers, includin开发者_Go百科g IE8. But ever since IE9 was released, it not longer works. The ondragstart event does not get triggered. Here is my code, using jQuery:
$('#mydiv')
.bind('selectstart', function(e) {
// Prevent text selection
return false;
})
.bind('dragstart', function(e) {
console.log('dragstart');
})
.bind('drag', function(e) {
console.log('drag');
})
.bind('dragend', function(e) {
console.log('dragend');
});
and the HTML
<div draggable="true">DnD this thing!</div>
I'm betting that didn't work in IE8, because neither IE8 or IE9 fully support HTML5 drag and drop, that's only been added in IE10 Developer Preview 2. The HTML5 API is based on the implementation of drag and drop in IE5, but there are some differences. Most pertinently, IE9 and before don't support the draggable
attribute on elements - the only things that can be dragged in IE9 are things which are draggable by default: text selections, links and images.
So for it to work in IE9 (or IE8) you need to add a link into your HTML (and that link must have an href
):
<div id="mydiv"><a draggable="true" href="#">DnD this thing!</a></div>
Your JavaScript should then work as expected with a few slight modifications:
$('#mydiv')
.bind('selectstart', function(e) {
// Prevent text selection
return false;
})
.bind('dragstart', function(e) {
e.originalEvent.dataTransfer.setData("Text", $(e.target).closest('div').attr('id'));
console.log('dragstart');
})
.bind('drag', function(e) {
console.log('drag');
})
.bind('dragend', function(e) {
console.log('dragend');
})
.bind('click', function(e) {
return false;
});
Here's an example which I've tested in Firefox and IE9.
精彩评论