📅  最后修改于: 2023-12-03 15:15:38.375000             🧑  作者: Mango
The ondragstart
event property is a JavaScript event handler that is triggered when an HTML element is being dragged. This event is used to initiate drag-and-drop operations in web applications.
The syntax for using the ondragstart
event property is as follows:
<element ondragstart="myFunction(event)">
Here, element
denotes the HTML element on which the event is being attached, and myFunction
is the name of the JavaScript function that is called when the event is triggered. The event
parameter is optional and it represents the event object that contains information about the event.
<!DOCTYPE html>
<html>
<head>
<title>ondragstart Event Example</title>
<script>
function startDrag(event) {
event.dataTransfer.setData("text", event.target.id);
}
</script>
<style>
#drag-element {
width: 100px;
height: 100px;
background-color: coral;
}
</style>
</head>
<body>
<h1>ondragstart Event Example</h1>
<p>Drag the coral-colored element to another location:</p>
<div id="drag-element" draggable="true" ondragstart="startDrag(event)"></div>
</body>
</html>
In this example, we have defined an HTML element with id drag-element
having draggable
attribute set to true
. On this element, we have attached the ondragstart
event property with a value of startDrag(event)
, which is the name of the JavaScript function that is called when the element is dragged.
The startDrag
function uses the setData
method of the dataTransfer
object to specify that the data being dragged is of type text
and its value is the id of the dragged element. This information will be used in the ondrop
event to determine what action to perform with the dragged element.
The ondragstart
event property is an important part of the drag-and-drop API in web applications. It allows developers to trigger custom actions when an HTML element is being dragged. With the help of this event, developers can implement sophisticated drag-and-drop functionality in their web applications.