【问题标题】:Make a draggable element whitout setting position to absolute将可拖动元素设置为绝对位置
【发布时间】:2021-05-24 10:26:23
【问题描述】:

我想在画布上拖动一些元素,然后返回它们的坐标。 所以元素应该彼此相邻出现,而不是我能够拖动它们。 我面临的问题是元素彼此出现,没有被空格分隔:

我正在使用来自https://www.w3schools.com/howto/howto_js_draggable.asp 的函数dragElement(element) 使我的元素可拖动。

//Make the DIV element draggagle:
dragElement(document.getElementById("mydiv"));
dragElement(document.getElementById("mydiv2"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    // if present, the header is where you move the DIV from:
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    // otherwise, move the DIV from anywhere inside the DIV:
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    // stop moving when mouse button is released:
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
#mydiv,
#mydiv2 {
  position: absolute;
  z-index: 9;
  background-color: #f1f1f1;
  text-align: center;
  border: 1px solid #d3d3d3;
}

#mydivheader,
#mydivheader2 {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}
<div class="container">
  <div id="markers" class="row">
    <div id="mydiv" class="col-sm-10">
      <div id="mydivheader">Click here to move</div>
      <p>Move</p>
      <p>this</p>
      <p>DIV</p>
    </div>
    <div id="mydiv2" class="col-sm-10">
      <div id="mydivheader2">Click here to move</div>
      <p>Move</p>
      <p>this</p>
      <p>DIV</p>
    </div>
  </div>
</div>

我尝试将 CSS 位置属性从绝对更改为相对,它使元素彼此相邻,但我不能再拖动它们了。

在我发布的代码中,我只有两个元素,但实际上,更多的新元素将使用 JS 代码动态创建。

这是我的 JS 代码:

//this list will be uploaded by the user      
var d = ["module1", "module2",.......,"module22"];

for(i in d){
  append_module_name_to_drag_div(d[i]);
  dragElement(document.getElementById(d[i]));  
}

function append_module_name_to_drag_div(module_name){
  var mydiv = document.createElement("div");
  mydiv.id=module_name;
  mydiv.className ='col-sm-10';

  var mydivmarker= document.createElement("div");
  mydivmarker.id=module_name+"header";
  mydivmarker.className ='mydivheader';
  
  var marker_image = new Image();
  marker_image.src = "http://www.clker.com/cliparts/w/O/e/P/x/i/map-marker-hi.png";
  marker_image.height = 45;
  marker_image.width = 35;
  
  mydivmarker.append(marker_image);
  mydiv.innerHTML=module_name;
  mydiv.append(mydivmarker);
  document.getElementById("markers").appendChild(mydiv);
}

【问题讨论】:

  • 您可以尝试使用位置relative 并使用transform: translate (tx, ty) 或transform: matrix() 移动它,但您需要这样的js
  • 是的,我正在使用JS,但我不明白如何添加transform: translate (tx, ty)?你能解释一下吗?
  • 使用边距代替top/left
  • @ZohirSalak 能否解释一下在哪里添加边距?
  • 您来自 W3schools 的代码使用绝对位置并更新属性 top 和 left,您希望拖动的元素影响文档的流动,因此从 css 中删除 position:absolute并更改代码以更新边距

标签: javascript html css position draggable


【解决方案1】:

元素出现在彼此之上,因为您的 #mydiv 声明了 position: absolute,这会将其从文档流中移除。按照 CSS 的规定,不流动的元素将被放置在流动的元素之上。

Greg 建议使用 CSS 函数 translate() 进行移动,而不是 position: absolute 和 top 等。这会将元素留在流中,这意味着它们仍然会被考虑。

由于translate()会在re-flow后生效(重新验证文档的流向),所以即使移动可拖动元素也不会影响你的布局。

如果您只对结果感兴趣,请跳过。但这里有更多信息。

W3Schools 曾经(是?)臭名昭著,因为有些过时,有时甚至提出了糟糕的建议,所以我建议在阅读他们的文章的基础上做一些研究。

现在,W3Schools' dragElement()-function 非常适合向后兼容,因为它是为 2011 年及更早版本的浏览器编写的。现在大多数(如果不是全部)浏览器都实现了 HTML5、CSS3 和(至少)ES6(JavaScript 规范),以及某些浏览器标准。

这意味着将支持以下(以及更多!):

  • 使用const/let。
    它们与var 之间的区别:它们声明了块范围变量,并且没有被提升。但是,使用它们将使调试更容易,并传达以下信息:
    • const 表示引用永远不会改变。
    • let 表示引用可能会更改。
  • 使用Element.querySelector() 搜索元素的后代。 (类似于Document.querySelector()。)
  • 使用addEventListener()/removeEventListener()。
    这解决了只能分配的问题 使用onevent-listeners 时,一个元素的事件监听器。
  • 使用(lambda) arrow-functions。经常可以用作 替代函数,但它们未提升。
  • 更多语义HTML标签!这一点非常重要,因为它们的使用是 (IMO) web-accessibility 的主要关注点。

一些题外话:

  • 我强烈建议在使用 CSS 库或类似库之前先学习编写自己的 CSS。
  • 我还强烈建议您学习(或至少阅读一次一次)所有 HTML 标记。这不仅可以帮助您理解语言,还可以让您创建可访问的页面,这对于 SEO 来说是必不可少的。
  • 我还想提一下 Google、Microsoft 和其他公司在 standard of marking up 上所做的各种努力。这也可能与 SEO 相关,但需要大量阅读材料。

重构

首先,我将删除所有已存在的 cmets,以便新的 cmets 可以解释更改。

有些人更喜欢'(单引号)而不是"(双引号)作为字符串,因为您更可能希望在字符串中使用" 而不是'。使用一个可以不转义地使用另一个。
我更喜欢 JS 中的 ',所以不要对我的更改为什么使用它们感到困惑。

我将所有var 实例替换为const 或let,具体取决于看起来更合适的情况。

代码现在将使用addEventListener()/removeEventListener() 而不是onevent-listener。

最重要的变化:

  • 在 HTML 中:
    • 可拖动元素现在使用draggable-class
    • 使用正确的标签:
      • 对于标题,使用&lt;header&gt;
      • 如果可拖动元素包含&lt;header&gt;,则将其设为&lt;section&gt;
  • 在 CSS 中:
  • 在 JS 中:

// Make all `.draggable` draggable
for (const el of document.querySelectorAll('.draggable'))
  dragElement(el);

// May be changed? Hence `let`
let d = ["module1", "module2", "module22"];

// Changed loop to for...of, because we only want to iterate over the array-elements
for (const el of d) {
  append_module_name_to_drag_div(el);
  dragElement(document.getElementById(el));  
}

function append_module_name_to_drag_div(module_name){
  const mydiv = document.createElement("div");

  mydiv.id = module_name;
  mydiv.className = 'col-sm-10 draggable'; // Added '.draggable'

  const mydivmarker = document.createElement("div");
  const marker_image = new Image();
  marker_image.src = "http://www.clker.com/cliparts/w/O/e/P/x/i/map-marker-hi.png";
  marker_image.height = 45;
  marker_image.width = 35;
  mydivmarker.append(marker_image);
  
  // Generally bad to use .innerHTML with user-generated content.
  // Prefer .innerText or .textContent.
  // Read more on:
  // https://developer.mozilla.org/en-US/docs/Web/API/Element/innerHTML#security_considerations
  mydiv.innerText = module_name;
  
  mydiv.append(mydivmarker);
  
  // Changed to .append(), try to stay consistent!
  // I suggest using .append() over .appendChild(), as the former allows
  // an arbitrary amount of arguments.
  document.getElementById("markers").append(mydiv);
}

// Originally from: "How to create a draggable HTML element" - W3Schools
// ( https://www.w3schools.com/howto/howto_js_draggable.asp )
function dragElement(el) {
  // We'll only need x- and y-positions; may/will change, hence `let`
  let xPos = 0;
  let yPos = 0;
  if (el.querySelector('header')) // Use Element.querySelector() to avoid using unnecessary IDs
    el.querySelector('header').addEventListener('mousedown', dragMouseDown);
  else
    el.addEventListener('mousedown', dragMouseDown);
  
  function dragMouseDown(event) {
    // The event-object will always be passed; no need to refer to window.event
    event.preventDefault();
    
    // No need to save initial mouse-position
    
    document.addEventListener('mouseup', closeDragElement);
    document.addEventListener('mousemove', elementDrag);
  }
  function elementDrag(event) {
    event.preventDefault();
    
    // New positions calculated using MouseEvent.(movementX|movementY)
    xPos += event.movementX;
    yPos += event.movementY;
    
    // Set position as translate() of .style.transform
    el.style.transform = `translate(${xPos}px, ${yPos}px)`;
  }
  function closeDragElement() {
    document.removeEventListener('mouseup', closeDragElement);
    document.removeEventListener('mousemove', elementDrag);
  }
}
/* Add enabling CSS for .draggable */
/* Enabling CSS:
 * Only declare properties when rules apply.
 */
/* Disabling CSS:
 * Declare all "default" properties.
 * Reset all then-unwanted properties.
 * May overwrite other rule's declarations in the process.
 */
/* Related: https://www.silvestar.codes/articles/you-want-a-single-enabling-selector-not-the-one-that-disables-the-rule-of-the-previous-one/ */

.draggable {width: fit-content} /* Default */
.draggable:not(section) {cursor: move} /* Enabling CSS */
section.draggable {
  border: 1px solid #d3d3d3;
  text-align: center;
  background-color: #f1f1f1;
}
section.draggable>header {
  padding: .625rem;
  color: #fff;
  background-color: #2196F3;
  cursor: move;
}
<div id="markers" class="row">
  <!--Change draggable sections to <section> where appropriate-->
  <section id="mydiv" class="col-sm-10 draggable"> <!--Add class "draggable" for styling-->
    <header>Click here to move</header> <!--May have a header; dragElement() now searches for such-->
    <p>Move</p>
    <p>this</p>
    <p>DIV</p>
  </section>
  
  <section id="mydiv2" class="col-sm-10 draggable">
    <header>Click here to move</header>
    <p>Move</p>
    <p>this</p>
    <p>DIV</p>
  </section>
</div>

【讨论】:

  • 感谢您的回答,但我不明白您的确切意思是什么?我应该改变整个代码结构吗?有什么方法可以只设置元素的位置并防止它们重叠?
  • @Abdoo.fe 老实说,我只是实现了一种使用 CSS 函数 translate() 的方法,而没有考虑您已经拥有的代码。因此,我的回答(到目前为止!)只是这种实现方式的一个示例,但我会尽快更新它。防止元素重叠可以通过检查它们是否重叠来完成,如果重叠,则重新计算位置(例如,将它们固定在另一个元素的边界框内)。
  • 如果您可以看看我的代码,看看我是否遗漏了导致元素重叠的内容,谢谢。
  • @Abdoo.fe 好吧,目前您使用position: absolute 将#mydiv 从流程中移除。这就是为什么它将位于其他元素之上的原因,因为流动的内容首先被布置,然后流出的内容在上面。 Greg 建议将元素留在流中(不使用position: absolute),并使用transform: translate(tx, ty) 允许拖动。
  • @Abdoo.fe 我的回答现在应该(至少)提供有关您的问题的必要信息,以及一些进一步的阅读材料和链接。希望对您有所帮助!
【解决方案2】:

我发现最好的方法是每次为每个元素设置top 和left,这样可以让每个元素处于单独的位置,而不会破坏可抓取的部分:

const d = ["module1", "module2", "module3", "module4", "module5"];



 for(i in d){
      append_module_name_to_drag_div(d[i],top,left);
      dragElement(document.getElementById(d[i]));  

      if(left<220){left=left+39;}
      //you can set here height and width: in my case 300 was the width of the container, 35 was the width of markers
      else{
        left=5;
        top=top+70;//70 height of marker
      }
    }

我修改了这个函数,增加了两个参数来指定顶部和左侧:

function append_module_name_to_drag_div(module_name,top,left){
  var mydiv = document.createElement("div");
  
  mydiv.id=module_name;
  mydiv.className ='col-sm-10';// 'col-md-3 col-lg-3 col-xl-3 col-sm-6';//'mydiv';

  var mydivmarker= document.createElement("div");
  mydivmarker.id=module_name+"header";
  mydivmarker.className ='mydivheader';// 'col-sm-4';//'mydivheader';
  var marker_image = new Image();
  marker_image.src = "http://www.clker.com/cliparts/w/O/e/P/x/i/map-marker-hi.png";
  marker_image.height = 45;
  marker_image.width = 35;
  mydivmarker.append(marker_image);

  // var p = document.createElement("p");
  mydiv.innerHTML=module_name;
  // mydiv.append(p);
  mydiv.append(mydivmarker);

  ///***
  // mydiv.style.cssFloat = "left";
  mydiv.style.left = left.toString()+"px";
  mydiv.style.top = top.toString()+"px";
///**** */

  document.getElementById("markers").appendChild(mydiv);
  var linebreak = document.createElement("br");
  document.getElementById("markers").appendChild(linebreak);
  
  
}

W3Schools 中的函数,除了 where(//设置元素的新位置:)这两行之外

function dragElement(elmnt) {
  
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}

【讨论】:

    【解决方案3】:

    原始 w3schools 示例

    您可以像链接的 w3schools 示例中提到的那样使用 position: absolute,但无需为绝对定位的元素定义 top、left 等,它们都具有相同的默认值:top: 0 和 left: 0。因此它们都出现在同一个位置,这导致彼此堆叠。

    如果为每个绝对定位的元素为top、left 等定义不同的值,则可以防止堆叠。例如:

    #mydiv2 {
      top: 170px;
    }
    

    这是针对您最初发布的问题的解决方案,其中包含两个硬编码的可拖动元素,但它不适合动态添加的内容。

    工作示例:

    为简单起见,我省略了函数dragElement() 中的第一个if ... else 块,并将事件侦听器直接附加到整个元素:

    elmnt.onmousedown = dragMouseDown;
    

    //Make the DIV element draggagle:
    dragElement(document.getElementById("mydiv2"));
    dragElement(document.getElementById("mydiv"));
    
    function dragElement(elmnt) {
      var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
      
      elmnt.onmousedown = dragMouseDown;
    
      function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
      }
    
      function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // calculate the new cursor position:
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        // set the element's new position:
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
      }
    
      function closeDragElement() {
        // stop moving when mouse button is released:
        document.onmouseup = null;
        document.onmousemove = null;
      }
    }
    #mydiv, 
    #mydiv2 {
      position :absolute;
      z-index: 9;
      background-color: #f1f1f1;
      text-align: center;
      cursor: move;
      border: 1px solid #d3d3d3;
    }
    
    #mydiv2 {
      top: 170px;
    }
    
    #mydivheader, 
    #mydivheader2 {
      padding: 10px;
      z-index: 10;
      background-color: #2196F3;
      color: #fff;
    }
    <div class="container">
    <div class="row">
      <div id="mydiv" class="col-sm-10">
        <div id="mydivheader">Click here to move</div>
        <p>Move</p>
        <p>this</p>
        <p>DIV</p>
      </div>
      <div id="mydiv2" class="col-sm-10">
        <div id="mydivheader2">Click here to move</div>
        <p>Move</p>
        <p>this</p>
        <p>DIV</p>
      </div>
    </div>
    </div>

    使用transform: translate()

    基本实现

    对于动态添加的内容(或任何其他不使用top、left 等的原因),最好使用transform: translate() 并省略position: absolute,以便元素保持在原位并且可以不要堆积。

    要实现这一点,您只需从旧的translate-values 中减去原始计算,然后用该减法的值覆盖(以保存它们以供下一个函数调用):

    pos1 = pos1 - (pos3 - e.clientX);
    pos2 = pos2 - (pos4 - e.clientY);
    

    最后,您必须将出现样式的两行从 top 和 left 更改为带有 translate 的一行:

    elmnt.style.transform = 'translate(' + (pos1) + "px, " + (pos2) + "px)";
    

    工作示例:

    我将过时的var 替换为let,因为变量会改变。

    //Make the DIV element draggagle:
    dragElement(document.getElementById("mydiv2"));
    dragElement(document.getElementById("mydiv"));
    
    function dragElement(elmnt) {
      let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
      
      elmnt.onmousedown = dragMouseDown;
    
      function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
      }
    
      function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // calculate the new cursor position:
        pos1 = pos1 - (pos3 - e.clientX);
        pos2 = pos2 - (pos4 - e.clientY);
        pos3 = e.clientX;
        pos4 = e.clientY;
        // set the element's new position:
        elmnt.style.transform = 'translate(' + (pos1) + "px, " + (pos2) + "px)";
      }
    
      function closeDragElement() {
        // stop moving when mouse button is released:
        document.onmouseup = null;
        document.onmousemove = null;
      }
    }
    #mydiv,
    #mydiv2 {
      width: 160px;
      background-color: #f1f1f1;
      text-align: center;
      cursor: move;
      border: 1px solid #d3d3d3;
    }
    
    #mydivheader,
    #mydivheader2 {
      padding: 10px;
      background-color: #2196F3;
      color: #fff;
    }
    <div class="container">
      <div class="row">
        <div id="mydiv" class="col-sm-10">
          <div id="mydivheader">Click here to move</div>
          <p>Move</p>
          <p>this</p>
          <p>DIV</p>
        </div>
        <div id="mydiv2" class="col-sm-10">
          <div id="mydivheader2">Click here to move</div>
          <p>Move</p>
          <p>this</p>
          <p>DIV</p>
        </div>
      </div>
    </div>

    口语变量

    w3schools 示例中的变量名称pos1, pos2, pos3, pos4 不是很直观。因此,应将它们重命名以便于理解它们的用途:translate = { x: 0, y: 0 } 和 client = { x: 0, y: 0 }。

    工作示例:

    //Make the DIV element draggagle:
    dragElement(document.getElementById("mydiv2"));
    dragElement(document.getElementById("mydiv"));
    
    function dragElement(elmnt) {
      let translate = { x: 0, y: 0 };
      let client = { x: 0, y: 0 };
      
      elmnt.onmousedown = dragMouseDown;
    
      function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        client.x = e.clientX;
        client.y = e.clientY;
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
      }
    
      function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // calculate the new cursor position:
        translate.x = translate.x - (client.x - e.clientX);
        translate.y = translate.y - (client.y - e.clientY);
        client.x = e.clientX;
        client.y = e.clientY;
        // set the element's new position:
        elmnt.style.transform = 'translate(' + (translate.x) + "px, " + (translate.y) + "px)";
      }
    
      function closeDragElement() {
        // stop moving when mouse button is released:
        document.onmouseup = null;
        document.onmousemove = null;
      }
    }
    #mydiv,
    #mydiv2 {
      width: 160px;
      border: 1px solid #d3d3d3;
      text-align: center;
      cursor: move;
      background-color: #f1f1f1;
    }
    
    #mydivheader,
    #mydivheader2 {
      padding: 10px;
      background-color: #2196F3;
      color: #fff;
    }
    <div class="container">
      <div class="row">
        <div id="mydiv" class="col-sm-10">
          <div id="mydivheader">Click here to move</div>
          <p>Move</p>
          <p>this</p>
          <p>DIV</p>
        </div>
        <div id="mydiv2" class="col-sm-10">
          <div id="mydivheader2">Click here to move</div>
          <p>Move</p>
          <p>this</p>
          <p>DIV</p>
        </div>
      </div>
    </div>

    最终实现

    为了演示您后来添加的用于动态添加可拖动元素的函数的代码,这里是最终实现。我将过时的var 替换为const,因为变量不会改变。

    工作示例:

    const d = ["module1", "module2", "module3", "module4", "module5"];
    
    for(i in d) {
      append_module_name_to_drag_div(d[i]);
      dragElement(document.getElementById(d[i]));  
    }
      
    function append_module_name_to_drag_div(module_name) {
      const mydiv = document.createElement("div");
      mydiv.id = module_name;
      mydiv.className = 'module col-sm-10';
    
      const mydivmarker = document.createElement("div");
      mydivmarker.id = module_name+"header";
      mydivmarker.className = 'mydivheader';
      
      const marker_image = new Image();
      marker_image.src = "http://www.clker.com/cliparts/w/O/e/P/x/i/map-marker-hi.png";
      marker_image.height = 45;
      marker_image.width = 35;
      
      mydivmarker.append(marker_image);
      mydiv.innerHTML = module_name;
      mydiv.append(mydivmarker);
      document.getElementById("markers").appendChild(mydiv);
    }
    
    function dragElement(elmnt) {
      let translate = { x: 0, y: 0 };
      let client = { x: 0, y: 0 };
      
      elmnt.onmousedown = dragMouseDown;
    
      function dragMouseDown(e) {
        e = e || window.event;
        e.preventDefault();
        // get the mouse cursor position at startup:
        client.x = e.clientX;
        client.y = e.clientY;
        document.onmouseup = closeDragElement;
        // call a function whenever the cursor moves:
        document.onmousemove = elementDrag;
      }
    
      function elementDrag(e) {
        e = e || window.event;
        e.preventDefault();
        // calculate the new cursor position:
        translate.x = translate.x - (client.x - e.clientX);
        translate.y = translate.y - (client.y - e.clientY);
        client.x = e.clientX;
        client.y = e.clientY;
        // set the element's new position:
        elmnt.style.transform = 'translate(' + (translate.x) + "px, " + (translate.y) + "px)";
      }
    
      function closeDragElement() {
        // stop moving when mouse button is released:
        document.onmouseup = null;
        document.onmousemove = null;
      }
    }
    .module {
      width: 80px;
      border: 1px solid #d3d3d3;
      text-align: center;
      cursor: move;
      background-color: #f1f1f1;
    }
    
    .mydivheader {
      padding: 10px;
      background-color: #2196F3;
      color: #fff;
    }
    <div class="container">
      <div id="markers" class="row">
      </div>
    </div>

    【讨论】:

    • 感谢您的回答,但是我如何定位许多将使用 JS 代码动态创建的新元素,
    • 如果您要显示动态创建元素的代码,则可以回答这个问题...
    • 我已经编辑了问题并添加了 JS 代码
    • @ab.fe 我更新了我的答案。请提供反馈。
    • 感谢您的回答,我在两天前解决了这个问题,每次在循环中为每个元素修复 left 和 top。你也是这样做的吗,我希望这对将来的人有帮助,我也忘了发布我的解决方案,再次感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-18
    • 2011-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-28
    相关资源
    最近更新 更多