0

как сделать так чтобы красный div при удержании левой кнопки мыши работал так а не при mousemove

const cursor = document.querySelector('.cursor');

document.addEventListener( 'mousemove', e => {
  cursor.style.left = e.clientX + 'px';
  cursor.style.top = e.clientY + 'px';
});
.cursor {
  width: 30px;
  height: 30px;
  transform: translate(-50%,-50%);
  position: absolute;
  background-color: red;
}
<div class="cursor"></div>

1

1 ответ 1

1

В грубом приближении так:

const cursor = document.querySelector('.cursor');
let canDrag = false;

document.addEventListener( 'mousemove', e => {
  if (!canDrag)
    return;
    
  cursor.style.left = e.clientX + 'px';
  cursor.style.top = e.clientY + 'px';
});

document.addEventListener( 'mouseup', e => canDrag = false);
cursor.addEventListener( 'mousedown', e => canDrag = true);
.cursor {
  width: 30px;
  height: 30px;
  transform: translate(-50%,-50%);
  position: absolute;
  background-color: red;
}
<div class="cursor"></div>

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.