简体   繁体   English

我该如何修理移动方块 - javascript

[英]How can I repair moving square - javascript

I want to ask you for help.我想请你帮忙。 I'm creating a moving square that have to work in this way:我正在创建一个必须以这种方式工作的移动方块:

  1. I'm grabbing it我抓住它
  2. It follows my cursor它遵循我的 cursor
  3. It stays in place where I moused up它停留在我鼠标悬停的地方

But I have a problem with the second point because the square is lagging when I'm using offsetX / Y. I discovered that the reason is the cursor on the square, because then the offset stops counting the axes X/Y.但是我对第二点有疑问,因为当我使用 offsetX/Y 时正方形滞后。我发现原因是正方形上的 cursor,因为那时偏移停止计算 X/Y 轴。 What can I do with it?我能用它做什么? When I move square to left or top, then it's ok.当我向左或顶部移动正方形时,就可以了。

HTML CODE: HTML 代码:

 <div class="container">
        <div class="square">
        </div>
    </div>

CSS: CSS:

body {
    padding: 0;
    margin: 0;
    width: 100vw;
    height: 100vh;
    background: bisque;
    display: flex;
    justify-content: center;
    align-items: center;
}

.container {
    width: 80vw;
    height: 80vh;
    border: 1px solid rgb(255, 122, 122);
    position: relative;
    overflow: hidden;
}

.square {
    width: 100px;
    height: 100px;
    background: blueviolet;
    cursor: pointer;
    position: relative;
}

JAVASCRIPT: JAVASCRIPT:

const square = document.querySelector('.square')
const container = document.querySelector('.container')


square.addEventListener('mousedown', createClass);
square.addEventListener('mouseup', removeClass);
container.addEventListener('mousemove', movingSquare);


// ADDING CLASS 'ACTIVE'
function createClass(e) {
    e.target.className = "square active";
}

// MOVING SQUARE
function movingSquare (e) {

        if (square.classList.contains('active')) {
        square.style.transform = `translate(${e.offsetX}px, ${e.offsetY}px)`;
        // square.style.left = e.offsetX + 'px';
        // square.style.top = e.offsetY + 'px';
    }   
}

// REMOVING CLASS 'ACTIVE'
function removeClass(e) {
    e.target.className = "square"
}

I can see a possible advantage of of using .offset values but I prefer to use clientX and clientY values.我可以看到使用.offset值的可能优势,但我更喜欢使用clientXclientY值。 It does require adjustment to allow for the positions of the parent element but is not difficult.它确实需要调整以允许父元素的位置,但并不困难。

In my snippet, instead of adding and removing classes, I access the .left and .top style properties of the element.在我的代码片段中,我没有添加和删除类,而是访问元素的.left.top样式属性。 A class name could be added if you want to change other aspects.如果要更改其他方面,可以添加 class 名称。

Like in your code I use event listeners for mousedown , mousemove , and mouseup .就像在您的代码中一样,我使用mousedownmousemovemouseup的事件侦听器。

In the mousedown event I set a boolean flag true if the target element is the moveable box (this equates to your class addition).mousedown事件中,如果目标元素是可移动框,我将boolean标志设置为true (这等同于您的 class 添加)。 I also set .client cursor positions for the start, and update the initial left and top values (relative to its parent container by subtraction) for the moveable element.我还为开始设置.client位置,并更新了可移动元素的初始lefttop值(相对于其父容器减去)。

This allows the mousemove listener to update (provided the target flag was set true ) the style left and top properties by an amount equal to the movement of the cursor coordinates since the mousedown was made.这允许mousemove侦听器更新(假设目标标志设置为true )样式lefttop属性的数量等于自mousedown以来 cursor 坐标的移动量。

 const box = document.getElementsByClassName('square')[0]; let downInBox=false; let initialLeft = 0; let initialTop = 0; let deltaX = 0; let deltaY = 0; let startX = 0; let startY = 0; document.addEventListener('mousedown', event => { if (event.target == box ) { downInBox=true; initialLeft = parseInt(box.getBoundingClientRect().left - box.parentElement.getBoundingClientRect().left); initialTop = parseInt(box.getBoundingClientRect().top - box.parentElement.getBoundingClientRect().top); startX = event.clientX; startY = event.clientY; } // end if }); // end mousedown; document.addEventListener('mouseup', event => { downInBox=false; }); // end mouseup; document.addEventListener('mousemove', event => { if (downInBox) { deltaX = startX-event.clientX; deltaY = startY-event.clientY; box.style.left = `${initialLeft-deltaX}px`; box.style.top = `${initialTop-deltaY}px`; } // end if; }); // end mousemove;
 body { padding: 0; margin: 0; width: 100vw; height: 100vh; background: bisque; display: flex; justify-content: center; align-items: center; }.container { width: 80vw; height: 80vh; border: 1px solid rgb(255, 122, 122); position: relative; overflow: hidden; }.square { width: 100px; height: 100px; background: blueviolet; cursor: pointer; position: relative; left: 0px; top: 0px; }
 <div class="container"> <div class="square"> </div> </div>

The mouseup listener simply resets the flag false (equivalent to you removing the class). mouseup侦听器只是将标志重置为false (相当于您删除了该类)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM