javascript 在前端使用mousedown事件移动正方形

cyej8jka  于 2023-01-01  发布在  Java
关注(0)|答案(3)|浏览(170)

仅仅通过使用addEventListener来练习一些前端的东西。我在这里试图实现的是:单击该正方形,然后按住鼠标将其移动到页面上的另一个位置,然后松开鼠标停止移动。2该正方形似乎只向一个方向移动,这有点不对劲。3此处需要帮助。

#square_cursor {
  position: relative;
  left: 109px;
  top: 109px;
  height: 50px;
  width: 50px;
  background-color: rgb(219, 136, 136);
  border: 5px rgb(136, 219, 219) solid;
  cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Drag and Drop</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div id='square_cursor'></div>
  <script>
    let mouse_over_detector = false; //move the mouse over WITHOUT clicking
    let mouse_click_detector = false; //clicking the mouse WITHOUT moveover
    let drag_detector = false; //move and holding the mouse together

    let window_click_detector = false;
    let window_motion_detector = false;

    let position_x = 0;
    let position_y = 0;

    let new_position_x = 0;
    let new_position_y = 0;

    window.addEventListener('mousedown', () => {
      window_click_detector = true;
    })

    window.addEventListener('mouseup', () => {
      window_click_detector = false;
      brick.style.backgroundColor = 'rgb(219, 136, 136)';
    })

    let brick = document.getElementById('square_cursor');

    //done
    brick.addEventListener('mousedown', (event) => {
      position_x = event.clientX;
      position_y = event.clientY;
      mouse_click_detector = true;
      brick.style.backgroundColor = 'yellow';
    })

    brick.addEventListener('mousemove', (event) => {
      if (mouse_click_detector === true) {
        new_position_x = event.clientX;
        new_position_y = event.clientY;
        dragAndDrop(position_x, position_y, event.offsetX, event.offsetY);

      }
    });

    brick.addEventListener('mouseout', () => {
      mouse_over_detector = false;
      mouse_click_detector = false;
    })

    brick.addEventListener('mouseup', () => {
      mouse_click_detector = false;
    })

    function dragAndDrop(a, b, c, d) {
      console.log('new x: ')
      console.log(a - c);
      console.log('new y: ')
      console.log(b - d);
      brick.style.left = a - c + 'px'
      brick.style.top = b - d + 'px';
    }
  </script>
</body>

</html>
a9wyjsp7

a9wyjsp71#

今天早上只用addEventListener woohoooo就解决了!
所以这里的关键是,首先,能够识别DOM层次结构,其次,知道clientX***对所选元素***做什么。
但我还是会投票给第一个答案。

#square_cursor{
    position:absolute;
    left:109px;
    top:109px;
    height:50px;
    width:50px;
    background-color: rgb(219, 136, 136);
    border:5px rgb(136, 219, 219) solid;
    cursor: pointer;
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Drag and Drop</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>
  <div id='square_cursor'></div>
  <script>
    let mouse_click_detector = false; //clicking the mouse WITHOUT moveover
    let window_click_detector = false;

    let position_x = 0;
    let position_y = 0;
    let click_position_x = 0;
    let click_position_y = 0;

    let brick = document.getElementById('square_cursor');

    brick.addEventListener('mousedown', () => {
      mouse_click_detector = true
    })

    window.addEventListener('mouseup', () => {
      mouse_click_detector = false;
      window_click_detector = false;
      brick.style.backgroundColor = 'rgb(219, 136, 136)';
    })

    window.addEventListener('mousedown', (event) => {
      if (mouse_click_detector === true) {
        window_click_detector = true;
        brick.style.backgroundColor = 'yellow';
        click_position_x = event.offsetX;
        click_position_y = event.offsetY;
      }
    })

    window.addEventListener('mousemove', (event) => {
      if (mouse_click_detector === true) {
        position_x = event.clientX;
        position_y = event.clientY;
        brick.style.left = position_x - click_position_x + 'px';
        brick.style.top = position_y - click_position_y + 'px';
      }
    })
  </script>
</body>

</html>

"最个人化的就是最有创造力的"---马丁。斯科塞斯

dgsult0t

dgsult0t2#

像这样的事...

//Make the DIV element draggable:
dragElement(document.getElementById("mydiv"));

function dragElement(elmnt) {
  var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  if (document.getElementById(elmnt.id + "header")) {
    /* if present, the header is where you move the DIV from:*/
    document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  } else {
    /* otherwise, move the DIV from anywhere inside the DIV:*/
    elmnt.onmousedown = dragMouseDown;
  }

  function dragMouseDown(e) {
    e = e || window.event;
    e.preventDefault();
    // get the mouse cursor position at startup:
    pos3 = e.clientX;
    pos4 = e.clientY;
    document.onmouseup = closeDragElement;
    // call a function whenever the cursor moves:
    document.onmousemove = elementDrag;
  }

  function elementDrag(e) {
    e = e || window.event;
    e.preventDefault();
    // calculate the new cursor position:
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    // set the element's new position:
    elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
    elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  }

  function closeDragElement() {
    /* stop moving when mouse button is released:*/
    document.onmouseup = null;
    document.onmousemove = null;
  }
}
#mydiv {
  
  position: absolute; /* NECESSARY */
  background-color: dodgerblue;
  border: 1px solid #d3d3d3;
  height: 20px;
  width: 20px;
}
<div id="mydiv">
  </div>
3qpi33ja

3qpi33ja3#

最简代码,
通过transform: translate(x,y)简化计算。

const myDiv  = document.querySelector('#my-div');
myDiv.ref_ms = { x: 0, y: 0 };

myDiv.addEventListener('mousedown', (e) =>
  {
  myDiv.ref_ms.x = e.clientX;
  myDiv.ref_ms.y = e.clientY;
  myDiv.classList.add('movCursor')

  if (myDiv.style.transform !== '')
    {
    let [ mx, my ] = myDiv.style.transform.match(/-?\d*\.?\d+/g).map(Number);
    myDiv.ref_ms.x -= mx;
    myDiv.ref_ms.y -= my;
    }
  })
window.addEventListener('mousemove', e =>
  {
  if (myDiv.classList.contains('movCursor')
    && e.clientX > 0 && e.clientY > 0 )
    {
    myDiv.style = `transform: translate(${e.clientX - myDiv.ref_ms.x}px, ${e.clientY - myDiv.ref_ms.y}px);`;
    }
  })
window.addEventListener('mouseup', () =>
  {
  myDiv.classList.remove('movCursor')
  })
#my-div {
  background : dodgerblue;
  border     : 1px solid #d3d3d3;
  height     : 50px;
  width      : 50px;
  margin     : 30px;
  cursor     : grab;
  }
.movCursor {
  cursor : grabbing !important;
  }
<div id="my-div"></div>

相关问题