HTML5 to achieve drag effect, detailed explanation of the principle and case implementation

Li Honghong 2020-11-11 17:37:05
html5 html achieve drag effect


 

As shown in the figure above , We can drag and drop images and hyperlinks from the blog Garden website .

stay HTML5 In the specification of , We can do this by adding  draggable="true"  To set whether the element can be dragged or not , The picture 、 Links are enabled by default .

1、 Drag and drop elements

The page has  draggable="true"  Attribute elements .

Examples are as follows :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="css/font-awesome.min.css">
<style>
.box1{
width: 200px;
height: 200px;
background-color: green;
}
</style>
</head>
<body>
<!-- to box1 Add drag properties -->
<div class="box1" draggable="true"></div>
</body>
</html>

The effect is as follows :

 

 

Above picture , We give box1 Added draggable="true"  After the attributes , Find out box1 It can be dragged . But what's to be done after dragging and dropping ? This involves Event monitoring .

Event monitoring of drag and drop elements :( Apply to drag and drop elements )

  • ondragstart Call when drag starts
  • ondragleave  When When the mouse leaves the drag element call
  • ondragend  Call when drag ends
  • ondrag  The whole drag process calls

Code demonstration :

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.box {
width: 200px;
height: 200px;
background-color: green;
}
</style>
</head>
<body>
<div class="box" draggable="true"></div>
<script>
var box = document.querySelector('.box');
// Binding drag and drop Events 
// Drag starts 
box.ondragstart = function () {
console.log(' Drag starts .');
}
// Drag away : Triggered when the mouse leaves the dragged element 
box.ondragleave = function () {
console.log(' Drag away ..');
}
// Drag end 
box.ondragend = function () {
console.log(' Drag end ...');
console.log("---------------");
}
box.ondrag = function () {
console.log(' Drag and drop ');
}
</script>
</body>
</html>

The effect is as follows :

 

 

Print the results :

 

 

2、 Target element

for instance , You want to put elements A Drag to the element B in , So the element B It's the target element .

Any element in the page can be the target element .

Event listening for the target element :( Apply to target elements )

  • ondragenter  Called when the drag element enters
  • ondragover  When the drag element stays on the target element , It's going to trigger all the time ( Whether the drag element is moving or not )
  • ondrop  Called when you release the mouse over the target element
  • ondragleave  Called when the mouse leaves the target element

Code demonstration :

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.one {
width: 100px;
height: 100px;
border: 1px solid #000;
background-color: green;
}
.two {
position: relative;
width: 200px;
height: 200px;
left: 300px;
top: 100px;
border: 1px solid #000;
background-color: red;
}
</style>
</head>
<body>
<div class="one" draggable="true"></div>
<div class="two"></div>
<script>
var two = document.querySelector('.two');
// Drag event of the target element 
// Triggered when the dragged element enters 
two.ondragenter = function () {
console.log(" coming .");
}
// Triggered when the dragged element leaves 
two.ondragleave = function () {
console.log(" go ..");
}
// When dragging elements in On the target element , Continuous trigger 
two.ondragover = function (e) {
// Default behavior to prevent drag and drop events 
e.preventDefault(); //【 important 】 Be sure to add this line of code , otherwise , Later methods ondrop() Unable to trigger .
console.log("over...");
}
// When you release the mouse over the target element, it triggers 
two.ondrop = function () {
console.log(" Let go of the mouse ....");
}
</script>
</body>
</html>

Effect demonstration :

 

 

Be careful , In the top code , We added event.preventDefault() This method . If there is no such way , Back ondrop() Method cannot trigger . As shown in the figure below :

 

 

As shown in the figure above , Even the shape of the cursor tells us , Can't continue in the target element .

summary : If you want the drag element to do something in the target element , It has to be in  ondragover()  Riga event.preventDefault() This line of code .

Case study : Drag and drop exercise

Full code :

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
.one {
width: 400px;
height: 400px;
border: 1px solid #000;
}
.one > div, .two > div {
width: 98px;
height: 98px;
border: 1px solid #000;
border-radius: 50%;
background-color: red;
float: left;
text-align: center;
line-height: 98px;
}
.two {
width: 400px;
height: 400px;
border: 1px solid #000;
position: absolute;
left: 600px;
top: 200px;
}
</style>
</head>
<body>
<div class="one">
<div draggable="true">1</div>
<div draggable="true">2</div>
<div draggable="true">3</div>
<div draggable="true">4</div>
<div draggable="true">5</div>
<div draggable="true">6</div>
<div draggable="true">7</div>
<div draggable="true">8</div>
</div>
<div class="two"></div>
<script>
var boxs = document.querySelectorAll('.one div');
// Temporary boxes Used to hold the element currently dragged 
var two = document.querySelector('.two');
var temp = null;
// to 8 Small boxes are bound to drag and drop events respectively 
for (var i = 0; i < boxs.length; i++) {
boxs[i].ondragstart = function () {
// Keep the current drag element 
temp = this;
console.log(temp);
}
boxs[i].ondragend = function () {
// When the drag is over , Empty temp
temp = null;
console.log(temp);
}
}
// Drag event of the target element 
two.ondragover = function (e) {
// The default behavior to prevent drag and drop 
e.preventDefault();
}
// When you release the mouse over the target element, it triggers 
two.ondrop = function () {
// Append the dragged element to two Come inside 
this.appendChild(temp);
}
</script>
</body>
</html>

The effect is as follows :

 

版权声明
本文为[Li Honghong]所创,转载请带上原文链接,感谢

  1. [front end -- JavaScript] knowledge point (IV) -- memory leakage in the project (I)
  2. This mechanism in JS
  3. Vue 3.0 source code learning 1 --- rendering process of components
  4. Learning the realization of canvas and simple drawing
  5. gin里获取http请求过来的参数
  6. vue3的新特性
  7. Get the parameters from HTTP request in gin
  8. New features of vue3
  9. vue-cli 引入腾讯地图(最新 api,rocketmq原理面试
  10. Vue 学习笔记(3,免费Java高级工程师学习资源
  11. Vue 学习笔记(2,Java编程视频教程
  12. Vue cli introduces Tencent maps (the latest API, rocketmq)
  13. Vue learning notes (3, free Java senior engineer learning resources)
  14. Vue learning notes (2, Java programming video tutorial)
  15. 【Vue】—props属性
  16. 【Vue】—创建组件
  17. [Vue] - props attribute
  18. [Vue] - create component
  19. 浅谈vue响应式原理及发布订阅模式和观察者模式
  20. On Vue responsive principle, publish subscribe mode and observer mode
  21. 浅谈vue响应式原理及发布订阅模式和观察者模式
  22. On Vue responsive principle, publish subscribe mode and observer mode
  23. Xiaobai can understand it. It only takes 4 steps to solve the problem of Vue keep alive cache component
  24. Publish, subscribe and observer of design patterns
  25. Summary of common content added in ES6 + (II)
  26. No.8 Vue element admin learning (III) vuex learning and login method analysis
  27. Write a mini webpack project construction tool
  28. Shopping cart (front-end static page preparation)
  29. Introduction to the fluent platform
  30. Webpack5 cache
  31. The difference between drop-down box select option and datalist
  32. CSS review (III)
  33. Node.js学习笔记【七】
  34. Node.js learning notes [VII]
  35. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  36. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  37. 【JQuery框架,Java编程教程视频下载
  38. [jQuery framework, Java programming tutorial video download
  39. Vue Router根据后台数据加载不同的组件(思考-&gt;实现-&gt;不止于实现)
  40. Vue router loads different components according to background data (thinking - & gt; Implementation - & gt; (more than implementation)
  41. 【Vue,阿里P8大佬亲自教你
  42. 【Vue基础知识总结 5,字节跳动算法工程师面试经验
  43. [Vue, Ali P8 teaches you personally
  44. [Vue basic knowledge summary 5. Interview experience of byte beating Algorithm Engineer
  45. 【问题记录】- 谷歌浏览器 Html生成PDF
  46. [problem record] - PDF generated by Google browser HTML
  47. 【问题记录】- 谷歌浏览器 Html生成PDF
  48. [problem record] - PDF generated by Google browser HTML
  49. 【JavaScript】查漏补缺 —数组中reduce()方法
  50. [JavaScript] leak checking and defect filling - reduce() method in array
  51. 【重识 HTML (3),350道Java面试真题分享
  52. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  53. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  54. [re recognize HTML (3) and share 350 real Java interview questions
  55. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  56. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  57. 【重识 HTML ,nginx面试题阿里
  58. 【重识 HTML (4),ELK原来这么简单
  59. [re recognize HTML, nginx interview questions]
  60. [re recognize HTML (4). Elk is so simple