목차
拖拽文本 EDIT
拖拽链接 EDIT
拖拽HTML与XML EDIT
Dragging Files EDIT
Dragging Images EDIT
Dragging Nodes EDIT
Dragging Custom Data EDIT
Dragging files to an operating system folder EDIT
웹 프론트엔드 HTML 튜토리얼 拖拽类型_html/css_WEB-ITnose

拖拽类型_html/css_WEB-ITnose

Jun 21, 2016 am 08:49 AM

拖拽文本 EDIT

拖拽文本的时候,使用 text/plain类型。数据应该是被拖拽的字符串。例如:

event.dataTransfer.setData("text/plain", "This is text to drag")
로그인 후 복사

拖拽网页上的文本框内文本及已选文本是自动完成的,所以你不需要自己处理。

建议你总是添加 text/plain类型数据作为不支持其它类型的应用或投放目标的降级,除非没有可选的符合逻辑的文本。总是将纯文本类型添加在最后,因为这是最不具体的数据( as it is the least specific)。

在旧的代码中,你可能会遇到 text/unicode或 Text类型。这些与 text/plain类型是等效的,存储、获取到的都是纯文本数据。

拖拽链接 EDIT

链接需要包含两种类型的数据;第一种是 text/uri-list类型的URL,第二种是 text/plain类型的URL。两种类型要使用相同的数据,即链接的URL。例如:

var dt = event.dataTransfer;dt.setData("text/uri-list", "http://www.mozilla.org");dt.setData("text/plain", "http://www.mozilla.org");
로그인 후 복사

与之前一样,将 text/plain类型添加在最后,因为它不如uri类型具体。

注意URL类型是 uri-list,“uri”中包含的是“i”,而不是“l”。

拖拽多条链接时,你可以使用换行将每条链接分开。以井号(#)开头的行是注释,不应该认为是合法的URL。你可以使用注释来指明链接的含义,或保存与链接相关的标题。 text/plain版本的数据应该包含所有的链接但不应该包含注释。

例如:

http://www.mozilla.org#A second linkhttp://www.xulplanet.com
로그인 후 복사

这个text/uri-list数据样例包含两条链接和一条注释。

当得到一条拖放的链接,你需要确保你能处理包含多条链接以及注释的数据。出于便利考虑,特殊类型 URL可以用来获得 text/uri-list类型数据中的第一条合法的链接(译注:chrome则是得到 text/uri-list的完整数据)。你不应该使用 URL类型来添加数据,这样做只是设置了 text/uri-list 类型的数据。

var url = event.dataTransfer.getData("URL");
로그인 후 복사

你也可以使用Mozilla自定义的 text/x-moz-url类型。如果使用了,它需要添加在 text/uri-list类型之前。他保存链接的 URL,后面跟随链接的标题,之间只用断行隔开。例如:

http://www.mozilla.orgMozillahttp://www.xulplanet.comXUL Planet
로그인 후 복사

拖拽HTML与XML EDIT

HTML内容可以使用 text/html类型。这种类型的数据需要是序列化的HTML。例如,使用元素的 innerHTML属性值来设置这个类型的值是合适的。

XML内容可以使用 text/xml类型,但你要确保数据值是格式良好的XML。

你也可以包含使用 text/plain类型表示的HTML或XML的纯文本。该数据应该只包含文本内容而不包含源标签或属性。例如:

var dt = event.dataTransfer;dt.setData("text/html", "Hello there, <strong>stranger</strong>");dt.setData("text/plain", "Hello there, stranger");
로그인 후 복사

Dragging Files EDIT

A local file is dragged using the application/x-moz-filetype with a data value that is an nsIFileobject. Non-privileged web pages are not able to retrieve or modify data of this type. Because a file is not a string, you must use the mozSetDataAtmethod to assign the data. Similarly, when retrieving the data, you must use the mozGetDataAtmethod.

event.dataTransfer.mozSetDataAt("application/x-moz-file", file, 0);
로그인 후 복사

If possible, you may also include the file URL of the file using both the text/uri-listand/or text/plaintypes. These types should be added last so that the more specific application/x-moz-filetype has higher priority.

Multiple files will be received during a drop as mutliple items in the data transfer. See Dragging and Dropping Multiple Itemsfor more details about this.

The following example shows how to create an area for receiving dropped files:

<listbox ondragenter="return checkDrag(event)" ondragover="return checkDrag(event)" ondrop="doDrop(event)"/><script>function checkDrag(event){ return event.dataTransfer.types.contains("application/x-moz-file");}function doDrop(event){ var file = event.dataTransfer.mozGetDataAt("application/x-moz-file", 0); if (file instanceof Components.interfaces.nsIFile) event.currentTarget.appendItem(file.leafName);}</script>
로그인 후 복사

In this example, the event returns false only if the data transfer contains the application/x-moz-filetype. During the drop event, the data associated with the file type is retrieved, and the filename of the file is added to the listbox. Note that the instanceofoperator is used here as the mozGetDataAtmethod will return an nsISupportsthat needs to be checked and converted into an nsIFile. This is also a good extra check in case someone made a mistake and added a non-file for this type.

Dragging Images EDIT

Direct image dragging is not commonly done. In fact, Mozilla does not support direct image dragging on Mac or Linux platforms. Instead, images are usually dragged only by their URLs. To do this, use the text/uri-listtype as with other URL links. The data should be the URL of the image or a data URL if the image is not stored on a web site or disk. For more information about data URLs, see the data URL scheme.

As with other links, the data for the text/plaintype should also contain the URL. However, a data URL is not usually as useful in a text context, so you may wish to exclude the text/plaindata in this situation.

In chrome or other privileged code, you may also use the image/jpeg, image/pngor image/giftypes, depending on the type of image. The data should be an object which implements the nsIInputStreaminterface. When this stream is read, it should provide the data bits for the image, as if the image was a file of that type.

You should also include the application/x-moz-filetype if the image is located on disk. In fact, this a common way in which image files are dragged.

It is important to set the data in the right order, from most specific to least specific. The image type such as image/jpegshould come first, followed by the application/x-moz-filetype. Next, you should set the text/uri-listdata and finally the text/plaindata. For example:

var dt = event.dataTransfer;dt.mozSetDataAt("image/png", stream, 0);dt.mozSetDataAt("application/x-moz-file", file, 0);dt.setData("text/uri-list", imageurl);dt.setData("text/plain", imageurl);
로그인 후 복사

Note that the mozGetDataAtmethod is used for non-text data. As some contexts may only include some of these types, it is important to check which type is made available when receiving dropped images.

Dragging Nodes EDIT

Nodes and elements in a document may be dragged using the application/x-moz-nodetype. This data for the type should be a DOM node. This allows the drop target to receive the actual node where the drag was started from. Note that callers from a different domain will not be able to access the node even when it has been dropped.

You should always include a plain text alternative for the node.

Dragging Custom Data EDIT

You can also use other types that you make up for custom purposes. You should strive to always include a plain text alternative unless that object being dragged is specific to a particular site or application. In this case, the custom type ensures that the data cannot be dropped elsewhere.

Dragging files to an operating system folder EDIT

There are cases in which you may want to add a file to an existing drag event session, and you may also want to write the file to disk when the drop operation happens over a folder in the operating system when your code receives notification of the target folder's location. This only works in extensions (or other privileged code) and the data flavor "application/moz-file-promise" should be used. The following sample offers an overview of this advanced case:

// currentEvent is a given existing drag operation eventcurrentEvent.dataTransfer.setData("text/x-moz-url", URL);currentEvent.dataTransfer.setData("application/x-moz-file-promise-url", URL);currentEvent.dataTransfer.setData("application/x-moz-file-promise-filename", leafName);currentEvent.dataTransfer.mozSetDataAt('application/x-moz-file-promise',                  new dataProvider(success,error),                  0, Components.interfaces.nsISupports);function dataProvider(){} dataProvider.prototype = {  QueryInterface : function(iid) {    if (iid.equals(Components.interfaces.nsIFlavorDataProvider)                  || iid.equals(Components.interfaces.nsISupports))      return this;    throw Components.results.NS_NOINTERFACE;  },  getFlavorData : function(aTransferable, aFlavor, aData, aDataLen) {    if (aFlavor == 'application/x-moz-file-promise') {         var urlPrimitive = {};       var dataSize = {};         aTransferable.getTransferData('application/x-moz-file-promise-url', urlPrimitive, dataSize);       var url = new String(urlPrimitive.value.QueryInterface(Components.interfaces.nsISupportsString));       console.log("URL file orignal is = " + url);             var namePrimitive = {};       aTransferable.getTransferData('application/x-moz-file-promise-filename', namePrimitive, dataSize);       var name = new String(namePrimitive.value.QueryInterface(Components.interfaces.nsISupportsString));         console.log("target filename is = " + name);         var dirPrimitive = {};       aTransferable.getTransferData('application/x-moz-file-promise-dir', dirPrimitive, dataSize);       var dir = dirPrimitive.value.QueryInterface(Components.interfaces.nsILocalFile);         console.log("target folder is = " + dir.path);         var file = Cc['@mozilla.org/file/local;1'].createInstance(Components.interfaces.nsILocalFile);       file.initWithPath(dir.path);       file.appendRelativePath(name);         console.log("output final path is =" + file.path);         // now you can write or copy the file yourself...    }   }}
로그인 후 복사
<strong>来源:https://developer.mozilla.org</strong>
로그인 후 복사
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

인기 기사

R.E.P.O. 에너지 결정과 그들이하는 일 (노란색 크리스탈)
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. 최고의 그래픽 설정
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. 크로스 플레이가 있습니까?
1 몇 달 전 By 尊渡假赌尊渡假赌尊渡假赌

뜨거운 도구

메모장++7.3.1

메모장++7.3.1

사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경

드림위버 CS6

드림위버 CS6

시각적 웹 개발 도구

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

& lt; Progress & Gt의 목적은 무엇입니까? 요소? & lt; Progress & Gt의 목적은 무엇입니까? 요소? Mar 21, 2025 pm 12:34 PM

이 기사는 HTML & lt; Progress & Gt에 대해 설명합니다. 요소, 그 목적, 스타일 및 & lt; meter & gt의 차이; 요소. 주요 초점은 & lt; progress & gt; 작업 완료 및 & lt; meter & gt; Stati의 경우

& lt; datalist & gt의 목적은 무엇입니까? 요소? & lt; datalist & gt의 목적은 무엇입니까? 요소? Mar 21, 2025 pm 12:33 PM

이 기사는 HTML & LT; Datalist & GT에 대해 논의합니다. 자동 완성 제안을 제공하고, 사용자 경험을 향상시키고, 오류를 줄임으로써 양식을 향상시키는 요소. 문자 수 : 159

& lt; meter & gt의 목적은 무엇입니까? 요소? & lt; meter & gt의 목적은 무엇입니까? 요소? Mar 21, 2025 pm 12:35 PM

이 기사는 HTML & lt; meter & gt에 대해 설명합니다. 범위 내에 스칼라 또는 분수 값을 표시하는 데 사용되는 요소 및 웹 개발의 일반적인 응용 프로그램. & lt; meter & gt; & lt; Progress & Gt; 그리고 Ex

뷰포트 메타 태그는 무엇입니까? 반응 형 디자인에 중요한 이유는 무엇입니까? 뷰포트 메타 태그는 무엇입니까? 반응 형 디자인에 중요한 이유는 무엇입니까? Mar 20, 2025 pm 05:56 PM

이 기사는 모바일 장치의 반응 형 웹 디자인에 필수적인 Viewport Meta Tag에 대해 설명합니다. 적절한 사용이 최적의 컨텐츠 스케일링 및 사용자 상호 작용을 보장하는 방법을 설명하는 반면, 오용은 설계 및 접근성 문제로 이어질 수 있습니다.

& lt; iframe & gt; 꼬리표? 보안을 사용할 때 보안 고려 사항은 무엇입니까? & lt; iframe & gt; 꼬리표? 보안을 사용할 때 보안 고려 사항은 무엇입니까? Mar 20, 2025 pm 06:05 PM

이 기사는 & lt; iframe & gt; 외부 컨텐츠를 웹 페이지, 공통 용도, 보안 위험 및 객체 태그 및 API와 같은 대안을 포함시키는 태그의 목적.

HTML은 초보자를 위해 쉽게 배우나요? HTML은 초보자를 위해 쉽게 배우나요? Apr 07, 2025 am 12:11 AM

HTML은 간단하고 배우기 쉽고 결과를 빠르게 볼 수 있기 때문에 초보자에게 적합합니다. 1) HTML의 학습 곡선은 매끄럽고 시작하기 쉽습니다. 2) 기본 태그를 마스터하여 웹 페이지를 만들기 시작하십시오. 3) 유연성이 높고 CSS 및 JavaScript와 함께 사용할 수 있습니다. 4) 풍부한 학습 리소스와 현대 도구는 학습 과정을 지원합니다.

HTML, CSS 및 JavaScript의 역할 : 핵심 책임 HTML, CSS 및 JavaScript의 역할 : 핵심 책임 Apr 08, 2025 pm 07:05 PM

HTML은 웹 구조를 정의하고 CSS는 스타일과 레이아웃을 담당하며 JavaScript는 동적 상호 작용을 제공합니다. 세 사람은 웹 개발에서 의무를 수행하고 화려한 웹 사이트를 공동으로 구축합니다.

HTML의 시작 태그의 예는 무엇입니까? HTML의 시작 태그의 예는 무엇입니까? Apr 06, 2025 am 12:04 AM

anexampleStartingtaginhtmlis, whithbeginsaparagraph.startingtagsareessentialinhtmlastheyinitiate rements, definetheirtypes, andarecrucialforstructurituringwebpages 및 smanstlingthedom.

See all articles