Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

How to create a draggable HTML element with JavaScript and CSS?


เพื่อสร้างองค์ประกอบ HTML ที่ลากได้ (draggable) ด้วย JavaScript และ CSS โค้ดมีดังนี้

ตัวอย่าง

<!DOCTYPE html> <html> <style>    body {       font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;    }    .dragDiv {       position: absolute;       z-index: 9;       text-align: center;       border: 1px solid #d3d3d3;       padding: 30px;       cursor: move;       z-index: 10;       background-color: rgb(108, 24, 177);       color: #fff;       font-size: 20px;       font-weight: 500;    } </style> <body> <h1>Draggable DIV Element Example</h1> <h2>Click and drag the below element to move it around</h2> <div class="dragDiv"> This div can be moved around </div> <script>    dragElement(document.querySelector(".dragDiv"));    function dragElement(ele) {       var pos1 = 0,       pos2 = 0,       pos3 = 0,       pos4 = 0;       if (document.querySelector(ele.id + "header")) {          document.getElementById(             ele.id + "header"          ).onmousedown = dragMouseDown;       }       else {          ele.onmousedown = dragMouseDown;       }       function dragMouseDown(e) {          e = e || window.event;          e.preventDefault();          pos3 = e.clientX;          pos4 = e.clientY;          document.onmouseup = closeDragElement;          document.onmousemove = elementDrag;       }       function elementDrag(e) {          e = e || window.event;          e.preventDefault();          pos1 = pos3 - e.clientX;          pos2 = pos4 - e.clientY;          pos3 = e.clientX;          pos4 = e.clientY;          ele.style.top = ele.offsetTop - pos2 + "px";          ele.style.left = ele.offsetLeft - pos1 + "px";       }       function closeDragElement() {          document.onmouseup = null;          document.onmousemove = null;       }    } </script> </body> </html>

ผลลัพธ์

โค้ดข้างต้นจะสร้างผลลัพธ์ดังนี้ -

How to create a draggable HTML element with JavaScript and CSS?

เมื่อลาก div ไปวางตำแหน่งต่างๆ -

How to create a draggable HTML element with JavaScript and CSS?