Техника Drag-n-Drop с использованием jQuery. Смотреть что такое "Drag-and-drop" в других словарях

HTML Drag and Drop interfaces enable applications to use drag-and-drop features in browsers. The user may select draggable elements with a mouse, drag those elements to a droppable element, and drop them by releasing the mouse button. A translucent representation of the draggable elements follows the pointer during the drag operation.

For web sites, extensions, and XUL applications, you can customize which elements can become draggable , the type of feedback the draggable elements produce, and the droppable elements.

This overview of HTML Drag and Drop includes a description of the interfaces, basic steps to add drag-and-drop support to an application, and an interoperability summary of the interfaces.

Drag Events Event On Event Handler Fires when…
drag ondrag …a dragged item (element or text selection) is dragged.
dragend ondragend …a drag operation ends (such as releasing a mouse button or hitting the Esc key; see Finishing a Drag .)
dragenter ondragenter …a dragged item enters a valid drop target. (See Specifying Drop Targets .)
dragexit ondragexit …an element is no longer the drag operation"s immediate selection target.
dragleave ondragleave …a dragged item leaves a valid drop target.
dragover ondragover …a dragged item is being dragged over a valid drop target, every few hundred milliseconds.
dragstart ondragstart …the user starts dragging an item. (See Starting a Drag Operation .)
drop ondrop …an item is dropped on a valid drop target. (See Performing a Drop .)

Note: Neither dragstart nor dragend events are fired when dragging a file into the browser from the OS.

Interfaces The basics

This section is a summary of the basic steps to add drag-and-drop functionality to an application.

Identify what is draggable

Making an element draggable requires adding the draggable attribute and the ondragstart global event handler, as shown in the following code sample:

function dragstart_handler(ev) { // Add the target element"s id to the data transfer object ev.dataTransfer.setData("text/plain", ev.target.id); }

This element is draggable.

For more information, see:

Define the drag"s data

The application is free to include any number of data items in a drag operation. Each data item is a string of a particular type - typically a MIME type such as text/html .

Each drag event has a dataTransfer property that holds the event"s data. This property (which is a DataTransfer object) also has methods to manage drag data. The setData() method is used to add an item to the drag data, as shown in the following example.

Function dragstart_handler(ev) { // Add different types of drag data ev.dataTransfer.setData("text/plain", ev.target.innerText); ev.dataTransfer.setData("text/html", ev.target.outerHTML); ev.dataTransfer.setData("text/uri-list", ev.target.ownerDocument.location.href); }

  • For a list of common data types used in drag-and-drop (such as text, HTML, links, and files), see Recommended Drag Types .
  • For more information about drag data, see Drag Data .
Define the drag image

By default, the browser supplies an image that appears beside the pointer during a drag operation. However, an application may define a custom image with the setDragImage() method, as shown in the following example.

Function dragstart_handler(ev) { // Create an image and then use it for the drag image. // NOTE: change "example.gif" to a real image URL or the image // will not be created and the default drag image will be used. let img = new Image(); img.src = "example.gif"; ev.dataTransfer.setDragImage(img, 10, 10); }

Learn more about drag feedback images in:

Define the drag effect

The dropEffect property is used to control the feedback the user is given during a drag-and-drop operation. It typically affects which cursor the browser displays while dragging. For example, when the user hovers over a drop target, the browser"s cursor may indicate the type of operation that will occur.

Three effects may be defined:

  • copy indicates that the dragged data will be copied from its present location to the drop location.
  • move indicates that the dragged data will be moved from its present location to the drop location.
  • link indicates that some form of relationship or connection will be created between the source and drop locations.
  • During the drag operation, drag effects may be modified to indicate that certain effects are allowed at certain locations.

    The following example shows how to use this property.

    Function dragstart_handler(ev) { ev.dataTransfer.dropEffect = "copy"; }

    For more details, see:

    Define a drop zone

    By default, the browser prevents anything from happening when dropping something onto most HTML elements. To change that behavior so that an element becomes a drop zone or is droppable , the element must have both ondragover and ondrop event handler attributes.

    The following example shows how to use those attributes, and includes basic event handlers for each attribute.

    Где элементы GUI реализованы при помощи псевдографики) при помощи манипулятора «мышь » или сенсорного экрана .

    Способ реализуется путём «захвата» (нажатием и удержанием главной (первой , чаще левой) кнопки мыши) отображаемого на экране компьютера объекта, программно доступного для подобной операции, и перемещении его в другое место (для изменения расположения) либо «бросания» его на другой элемент (для вызова соответствующего, предусмотренного программой, действия). По отношению к окнам (также способным к перемещению подобным способом) данный термин обычно не употребляется.

    Базовыми действиями и самыми простыми примерами drag-and-drop действий являются: перемещение объекта, перемещение объекта в из панели в панель, хотя в современных операционных системах drag-and-drop получил широкое применение и является одним из главных способов взаимодействия с компьютером в графическом интерфейсе пользователя.

    Объектами для перемещения могут быть следующие элементы интерфейса : значки (иконки) Рабочего стола , плавающие панели инструментов , ярлыки программ в Панели задач (начиная с Win XP), элементы TreeView , текстовая строка, ячейка DataGridView., также элементы OLE . Перемещаться объекты могут как в пределах некоторой определённой области, в пределах одного окна , между панелями одного окна, так и между разными окнами.

    Событие перетаскивания должно инициироваться каким-либо действием пользователя. Чаще всего этим действием является нажатие левой кнопки мыши на элементе (событие это называется MouseDown), который может быть перемещен в своем контейнере. Некоторые компоненты обладают собственными событиями начала drag-n-drop - например, TreeView имеет событие ItemDrag.


    Wikimedia Foundation . 2010 .

    Смотреть что такое "Drag-and-drop" в других словарях:

      Drag and drop - 〈[ dræg ənd drɔ̣p] n.; ; unz.; EDV〉 das Anklicken eines Objektes, das auf dem Computerbildschirm (in eine andere Datei bzw. an eine andere Stelle) verschoben u. dort wieder losgelassen wird [<engl. drag „ziehen“ + and „und“ + drop „fallen… … Universal-Lexikon

      Форма выполнения каких либо действий в графических интерфейсах пользователя, подразумевающая использование компьютерной мыши. В переводе с английского означает буквально: тащи и бросай. Действие выполняется путем оперирования видимыми на экране… … Словарь бизнес-терминов

      drag and drop - (computing) To move an icon, file, etc across the screen using a mouse and release it in a different place (dragˈ and dropˈ adjective) Main Entry: drag … Useful english dictionary

      drag and drop - IT to move something from one area of a computer screen to another using the mouse: »The software allows you to drag and drop elements for the page images, text, etc. anywhere you want. Main Entry: drag … Financial and business terms

      drag-and-drop - UK US verb n.; Gen.: ; Pl.: unz.; EDV〉 das Anklicken eines Objektes, das auf dem Computerbildschirm (in eine andere Datei bzw. an eine andere Stelle) verschoben u. dort wieder losgelassen wird }