在Div内拖动元素

时间:2019-06-01 21:13:26

标签: javascript html

我一直在尝试解决此问题,但没有成功。

我在div内有一个元素,并且使该元素可拖动,但是当我拖动它时,它移动得太快,并且也不能随光标一起移动,所以我不知道为什么。我也尝试过将div以外的元素放在主体上,以使其完全正常。

调用函数:

element.addEventListener('mousedown',dragClass.mousedown);

拖动类别:

class drag{
 constructor(){}

 drag(e){
  var container = document.getElementsByClassName('container')[0];
  var element = document.getElementsByClassName('element')[0];
  e = e || window.event;
  e.preventDefault();

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

  element.style.top = (element.offsetTop - pos2) + "px";
  element.style.left = (element.offsetLeft - pos1) + "px";
  element.style.cursor = 'grabbing';
 }

 mousedown(e){
  var container = document.getElementsByClassName('container')[0];
  var element = document.getElementsByClassName('element')[0];
  if(e.target == element){
    e = e || window.event;
    e.preventDefault();

    element.style.cursor = 'grab';

    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = dragClass.closeDrag;
    document.onmousemove = dragClass.drag;
  }
 }

 closeDrag(){
  var element = document.getElementsByClassName('element')[0];
  document.onmouseup = null;
  document.onmousemove = null;
  element.style.cursor = 'default';
 }

}

CSS:

.container{
  position: relative;
  display: inline-block;
  overflow: hidden;
  width: 90%;
  height: 800px;
  left: 50%;
  transform: translate(-50%);
  margin-top: 50px;
  border: 1px solid #f1f1f1;
 }

 .element{
   display: block;
   position: relative;
   font-family: sans-serif;
   margin-left: 10px;
   margin-right: 10px;
   margin-top: 10px;
   margin-bottom: 10px;
   border: 1px solid black;
   outline: none;
   overflow: hidden;
   z-index: 4;
 }

0 个答案:

没有答案