DemychO
@DemychO
16 летний парень изучающий Python

Как сделать удержание элемента в том месте, где зажал мышкой на JavaScript?

Не получается написать всего 2 строчки так, чтобы они не ломали код. Нужно сделать сделать правильное позиционирование элемента по отношению к курсору, когда зажимаешь этот элемент, т.е. элемент не должен следовать за курсором верхним левым краем
Вот эти две строчки не получается правильно вставить, помогите пожалуйста:
let shiftX = event.clientX - value1.getBoundingClientRect().left;
let shiftY = event.clientY - value1.getBoundingClientRect().top;

HTML:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Anonymous+Pro&display=swap" rel="stylesheet">
    <title>SkyMath</title>
</head>
<body>
    <header>
        <h2 id="header">Pfkegf</h2>
    </header>
<section>

    <div class="zone_equation">
        <div class="container">

            <div class="part_left">


                <div class="value1" draggable="true">1</div>


                <div class="unknown_value drag"></div>
            </div>

            <div class="rovno">=</div>

            <div class="part_right">
                <div class="value2 drag"></div>
                <div class="none drag"></div>
            </div>

        </div>

</section>
</body>
<script src="script.js"></script>
</html>

JavaScript:
const value1 = document.querySelector('.value1')
const mousedown =(event)=> {
    value1.style.position = 'absolute';
    value1.style.zIndex = 1000;
    document.body.append(value1);

    document.addEventListener('mousemove', mouseMove)

    value1.addEventListener('mouseup', mouseUp)
}


// ПЕРЕДВИНУТЬ
function moveAt(x, y)
{

}
const mouseMove =(event)=> {

    value1.style.left = event.pageX  + 'px';
    value1.style.top = event.pageY  + 'px';
}
// ОТПУСТИТЬ
const mouseUp =(event)=> {
    document.removeEventListener('mousemove', mouseMove)
}

value1.addEventListener('mousedown', mousedown)
document.addEventListener('mouseup', mouseUp)


CSS:
*, *::before, *::after {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    width: 100%;
    margin: 0;
    color: black;
    background: white;
}

h1, h2, h3 {
    text-align: center;
}



#header {
    font-family: 'Anonymous Pro', monospace;

    padding: 10px 0;
    border-bottom: 1px solid #00FF47;
    box-shadow: 0 0 10px gray;
    margin: 0;
}

.container {
    display: flex;
    justify-content: center;
}

section {
    width: 100%;
    height: 100vh;
    text-align: center;
}
.zone_equation{
    margin: 0 20px;
}

.part_left {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    width: 70%;
    height: 100px;
    border: 1px solid orange;
    border-radius: 10px 0 0 10px;
    margin: 20px 0 0 0;
}

.part_right {
    display: flex;
    justify-content: left;
    align-items: center;
    width: 70%;
    height: 100px;
    border: 1px solid orange;
    border-radius: 0 10px 10px 0;
    margin: 20px 0 0 0;
}

.value1, .value2, .unknown_value {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 50px;
    height: 50px;
    background-color: white;
    border: 1px solid yellow;
    border-radius: 32%;
    margin: 2px;

    cursor: pointer;
}
.value1 {
    background-color: deepskyblue;
    border: none;
}
.none {
    width: 50px;
    height: 50px;
    border: 1px solid grey;
    background-color: white;
}



.rovno {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 5%;
    height: 100px;
    border: 1px solid orange;
    margin: 20px 0 0 0;
}
  • Вопрос задан
  • 66 просмотров
Решения вопроса 1
На этом сайте есть то, что вам нужно. Приложил код под ваш элемент:

var ball = document.querySelector('.value1');

ball.onmousedown = function(e) {

  var coords = getCoords(ball);
  var shiftX = e.pageX - coords.left;
  var shiftY = e.pageY - coords.top;

  ball.style.position = 'absolute';
  document.body.appendChild(ball);
  moveAt(e);

  ball.style.zIndex = 1000; 

  function moveAt(e) {
    ball.style.left = e.pageX - shiftX + 'px';
    ball.style.top = e.pageY - shiftY + 'px';
  }

  document.onmousemove = function(e) {
    moveAt(e);
  };

  ball.onmouseup = function() {
    document.onmousemove = null;
    ball.onmouseup = null;
  };

}

ball.ondragstart = function() {
  return false;
};

function getCoords(elem) {
  var box = elem.getBoundingClientRect();
  return {
    top: box.top + pageYOffset,
    left: box.left + pageXOffset
  };
}
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы