<header>
  <h2 class="title">Mouse Events: Перетягування та зміна розміру блоку</h2>
  <p class="description">Дозволяє користувачу перетягувати та змінювати розмір блоку за допомогою миші</p>
</header>
<main>
  <div class="result">
    <div class="draggable-box">
      Натисніть та тягніть мене
      <button id="toggleResize">Змінити режим розміру</button>
    </div>
  </div>
</main>
body {
  font-size: 16px;
  line-height: 1.5;
  font-family: monospace;
}

header {
  background-color: #f1f1f1;
  margin-bottom: 25px;
  padding: 15px;
  box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
}

header h2.title {
  padding-bottom: 15px;
  border-bottom: 1px solid #999;
}

header p.description {
  font-style: italic;
  color: #222;
}

.result {
  background-color: #f8f8f8;
  padding: 15px;
  box-shadow: 0px 0px 3px 0px rgba(118, 118, 118, 1);
}

.draggable-box {
  width: 150px;
  height: 150px;
  background-color: #0073e6;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  cursor: grab;
}

.draggable-box.resizable {
  cursor: nwse-resize;
}
const box = document.querySelector('.draggable-box');
const resizeToggle = document.getElementById('toggleResize');

let isDragging = false;
let isResizing = false;
let startX, startY, startWidth, startHeight;

box.addEventListener('mousedown', function(event) {
  if (box.classList.contains('resizable')) {
    // Почати зміну розміру
    isResizing = true;
    startX = event.clientX;
    startY = event.clientY;
    startWidth = box.offsetWidth;
    startHeight = box.offsetHeight;
  } else {
    // Почати перетягування
    isDragging = true;
    startX = event.clientX - box.offsetLeft;
    startY = event.clientY - box.offsetTop;
  }
  document.addEventListener('mousemove', onMouseMove);
  document.addEventListener('mouseup', onMouseUp);
});

function onMouseMove(event) {
  if (isDragging) {
    box.style.left = `${event.clientX - startX}px`;
    box.style.top = `${event.clientY - startY}px`;
    box.style.position = 'absolute';
  }
  if (isResizing) {
    box.style.width = `${startWidth + (event.clientX - startX)}px`;
    box.style.height = `${startHeight + (event.clientY - startY)}px`;
  }
}

function onMouseUp() {
  isDragging = false;
  isResizing = false;
  document.removeEventListener('mousemove', onMouseMove);
  document.removeEventListener('mouseup', onMouseUp);
}

// Перемикання режиму зміни розміру
resizeToggle.addEventListener('click', function() {
  box.classList.toggle('resizable');
  if (box.classList.contains('resizable')) {
    resizeToggle.textContent = 'Вимкнути зміну розміру';
  } else {
    resizeToggle.textContent = 'Змінити режим розміру';
  }
});

External CSS

This Pen doesn't use any external CSS resources.

External JavaScript

This Pen doesn't use any external JavaScript resources.