使用mousedown、mousemove、mouseup實現拖拽效果

如何實現一個元素的拖拽效果,使用原生的js實現,習慣了jquery的同窗們,大家本身寫了嗎?N久使用mvvm框架,不寫jquery的東西,感受本身徹底不會了。javascript

話很少說,直接上code。本例子以簡單的div爲例子。css

html

<div id="div">我是一個能夠退拽的div</div>

css

div {
  position: fixed;
  left: 0;
  top: 0;
  width: 100px;
  height: 100px;
  background: #999;
  padding: 10px;
  cursor: pointer;
}

javascript

window.onload = funtion() {
  const div = document.getElementById('div');
  let initPosition = {};


  div.addEventListener('mousedown', onMousedown);
  
  function onMousedown(event) {
    
    const { pageX, pageY } = event;
    initPosition = getPosition();

    document.addEventListener('mousemove', omMousemove);
    document.addEventListener('mouseup', onMouseUp);

  }

  function omMousemove(event) {
    const { pageX, pageY } = event;
    const { left, top} = calcPosition(pageX, pageY);

    div.style.cssText = `left:${left}px;top:${top}px;`;

  }

  function onMouseUp(event) {
    document.removeEventListener('mousemove', onMouseMove);
  }


  function calcPosition(pageX, pageY) {

    const { left, top, scrollLeft, maxCriticalX, maxCriticalY } = initPosition;

    let x = pageX - left;
    let y = pageY - top;

    if (x <= scrollLeft) {
      x = scrollLeft;
    }

    if (x >= maxCriticalX) {
      x = maxCriticalX;
    }

    if (y >= maxCriticalY) {
      y = maxCriticalY;
    }

    if ( y<=0 || maxCriticalY < 0) {
      y = 0;
    }

    return {
      left: x,
      top: y
    };
  }



  function getPosition() {
    const { left, top, width, height } = div.getBoundingClientRect();
    const { scrollLeft, scrollTop } = document.body;

    const maxCriticalX = scrollLeft + innerWidth - width;
    const maxCriticalY = scrollTop + innerHeight - height;

    return {
        left,
        top,
        scrollLeft,
        maxCriticalX,
        maxCriticalY
    };
  }
};
相關文章
相關標籤/搜索