美文网首页
用 mouse 事件写一个可拖曳的div

用 mouse 事件写一个可拖曳的div

作者: hzl的学习小记 | 来源:发表于2019-07-19 09:55 被阅读0次

用 mouse 事件写一个可拖曳的 div

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div id="xxx"></div>
</body>
</html>
div{
    border:1px solid red;
    position:absolute;
    top:0;
    left:0;
    width:100px;
    height:100px;
}

*{margin:0;padding:0;}
var position=null
var dragging = false;

xxx.addEventListener('mousedown',function(e){
    dragging = true;
    position = [e.clientX, e.clientY]
})

document.addEventListener('mousemove',function(e){
   if(dragging === false) return;
   const x = e.clientX;
   const y = e.clientY;
   const deltaX = x- position[0]
   const deltaY = y - position[1]
   const left = parseInt(xxx.style.left) || 0;
   const top = parseInt(xxx.style.top) || 0;
   xxx.style.left =left + deltaX + 'px'
   xxx.style.top =top + deltaY + 'px'
   position = [x,y]
})

document.addEventListener('mouseup',function(e){
    dragging = false
})

测试demo:
jsbin

相关文章

网友评论

      本文标题:用 mouse 事件写一个可拖曳的div

      本文链接:https://www.haomeiwen.com/subject/rfxjlctx.html