Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
532 views
in Technique[技术] by (71.8m points)

html - How to make <div>s in HTML5 draggable for Firefox?

I am playing around with the HTML5 features, and I want div's (and similar containers like articles, sections, etc.) to be draggable. Consider the following code:

<!DOCTYPE html>
<html>
<head>
  <title>A Simple Draggable Object</title>
</head>

<body>
    <h1>Test #1: A Simple Draggable Object</h1>
    <div draggable="true">This text should be draggable.</div>
</body>
</html>

I tested in OS X the following browsers: In Chrome 7.0 and Safari 5.0.2 I can successfully drag the text around, but in Firefox 3.6 and 4.0b6 I can neither drag the text nor mark it (as if it was usual text). Is this a bug or a feature? How do I achieve that Firefox lets me drag around these tags without using jQuery ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to HTML5 Doctor, this won't work in Firefox without some JS help.

The HTML 5 spec says it should be as simple as adding the following attributes to the markup of the elements in question:

draggable="true"

However, this doesn’t work completely for Safari or Firefox. For Safari you need to add the following style to the element:

[draggable=true] {
  -khtml-user-drag: element;
}

This will start working in Safari, and as you drag it will set a default, empty value with the dataTransfer object. However, Firefox won’t allow you to drag the element unless you manually set some data to go with it. To solve this, we need a dragstart event handler, and we’ll give it some data to be dragged around with:

var dragItems = document.querySelectorAll('[draggable=true]');

for (var i = 0; i < dragItems.length; i++) {
  addEvent(dragItems[i], 'dragstart', function (event) {
    // store the ID of the element, and collect it on the drop later on

    event.dataTransfer.setData('Text', this.id);
  });
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...