在 vanilla js 上拖放鼠标移动脚本

我正在编写一个拖放脚本,用于拖放带有“.draggable”类的块。问题是该块会定期粘在光标上并且不会脱落。如何编辑此脚本,以便可以用鼠标拖动所有具有“.draggable”类的块而不会出现此问题?

let elements = document.querySelectorAll('.draggable');


elements.forEach(function(el) {

  let mover = false,

    x, y, posx, posy, first = true;

  el.onmousedown = function() {

    mover = true;

  };

  el.onmouseup = function() {

    mover = false;

    first = true;

  };

  el.parentNode.onmousemove = function(e) {

    el.style.cursor = "move";

    if (mover) {

      if (first) {

        x = e.offsetX;

        y = e.offsetY;

        first = false;

      }


      posx = e.pageX - x;

      posy = e.pageY - y;

      el.style.left = posx + 'px';

      el.style.top = posy + 'px';

    }

  }

});

.draggable {

  position: absolute;

  z-index: 1;

  top: 100px;

}

<section class="dragscroll">

  <div class="draggable">

    <textarea></textarea>

   </div>

</section>


<section class="dragscroll">

  <div class="draggable">

    <textarea></textarea>

  </div>

</section>



www说
浏览 83回答 1
1回答

DIEA

很难说这有效,因为它很难产生错误,所以请让我知道这有效。我所做的只是document.addEventListener("mouseup", function() {&nbsp; &nbsp; mover = false;&nbsp; &nbsp; first = true;&nbsp; });let elements = document.querySelectorAll('.draggable');elements.forEach(function(el) {&nbsp; let mover = false,&nbsp; &nbsp; x, y, posx, posy, first = true;&nbsp; el.onmousedown = function() {&nbsp; &nbsp; mover = true;&nbsp; };&nbsp; document.addEventListener("mouseup", function() {&nbsp; &nbsp; mover = false;&nbsp; &nbsp; first = true;&nbsp; });/*&nbsp; document.onmouseup = function() {&nbsp; &nbsp; mover = false;&nbsp; &nbsp; first = true;&nbsp; };*/&nbsp; el.parentNode.onmousemove = function(e) {&nbsp; &nbsp; el.style.cursor = "move";&nbsp; &nbsp; if (mover) {&nbsp; &nbsp; &nbsp; if (first) {&nbsp; &nbsp; &nbsp; &nbsp; x = e.offsetX;&nbsp; &nbsp; &nbsp; &nbsp; y = e.offsetY;&nbsp; &nbsp; &nbsp; &nbsp; first = false;&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; posx = e.pageX - x;&nbsp; &nbsp; &nbsp; posy = e.pageY - y;&nbsp; &nbsp; &nbsp; el.style.left = posx + 'px';&nbsp; &nbsp; &nbsp; el.style.top = posy + 'px';&nbsp; &nbsp; }&nbsp; }});.draggable {&nbsp; position: absolute;&nbsp; z-index: 1;&nbsp; top: 100px;}<section class="dragscroll">&nbsp; <div class="draggable">&nbsp; &nbsp; <textarea></textarea>&nbsp; &nbsp;</div></section><section class="dragscroll">&nbsp; <div class="draggable">&nbsp; &nbsp; <textarea></textarea>&nbsp; </div></section>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript