Skip welcome & menu and move to editor
Welcome to JS Bin
Load cached copy from
 
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
<div id="drag"></div>
</body>
</html>
 
var dragFlag = false;
var position = null;
drag.addEventListener('mousedown', function(e) {
  dragFlag = true;
  position = [e.clientX, e.clientY];
})
// mousemove 与 mouseup 不能监听在元素上 快速拖到会有问题
document.addEventListener('mousemove', function(e) {
 if (dragFlag) {
    return;
  }
  const x = e.clientX;
  const y = e.clientY;
  const deltaX = x - position[0];
  const deltaY = y - position[1];
  // parseInt('')空转为 NaN
  // drag.style.left初始值为'0px'
  const left = parseInt(drag.style.left || 0, 10);
  const top = parseInt(drag.style.top || 0, 10);
  drag.style.left = left + deltaX + 'px';
  drag.style.top = top + deltaY + 'px';
  position= [x, y];
})
document.addEventListener('mouseup', function() {
    dragFlag = false;
})
Output

You can jump to the latest bin by adding /latest to your URL

Dismiss x
public
Bin info
anonymouspro
0viewers