كيفية إنشاء عناصر HTML القابلة للسحب

تعلم كيفية استخدام JavaScript و CSS لإنشاء عناصر HTML القابلة للسحب.

عنصر DIV القابل للسحب

انقر هنا لسحب

تحرك

هذا

DIV

إنشاء عنصر DIV القابل للسحب

الخطوة الأولى - إضافة HTML:

<!-- DIV القابلة للسحب -->
<div id="mydiv">
  <!-- يحتوي على DIV عنوان يحمل نفس الاسم لـ DIV القابلة للسحب، يتبعه "header" -->
  <div id="mydivheader">انقر هنا لسحب</div>
  <p>تحرك</p>
  <p>هذا</p>
  <p>DIV</p>
</div>

الخطوة الثانية - إضافة CSS:

النمط الوحيد المهم هو position: absolute;،الجزء المتبقي يرجى تحديد:

#mydiv {
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  border: 1px solid #d3d3d3;
  text-align: center;
{}
#mydivheader {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
{}

الخطوة الثالثة - إضافة JavaScript:

// جعل عنصر DIV قابلاً للسحب:
dragElement(document.getElementById("mydiv"));
function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    // إذا كان موجودًا، فإن العنوان هو الموقع الذي تتحرك منه DIV:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  }
    // إذا لم يكن كذلك، قم بتحريك DIV من أي موقع داخل DIV:
    elmnt.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;
    // تعيين موقع العنصر الجديد:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  {}
  function closeDragElement() {
    // عند إطلاق زر الفأرة يتوقف التحرك:
    document.onmouseup = null;
    document.onmousemove = null;
  {}
{}

جرب بنفسك