3

хочу реализовать перемещение всех блоков на JS, т.е нажал на один квадрат вместе с ним перемещаются другие. Из того что есть:

Создаёт квадрат 20 на 20 пикселей, раскидывает его рандомно в документе.

function createCoub(className){
  var div = document.createElement('div');
  div.className    = className;
  div.style.width  = '20px';
  div.style.height = '20px';
  div.style.backgroundColor = 'black'
  div.style.margin = "0px"
  div.style.position = "absolute";
  div.style.top = Math.floor(Math.random() * (1500 - 0)) + 0 + "px";
  div.style.left = Math.floor(Math.random() * (2000 - 0)) + 0 + "px" 

  return div;
}

Создаёт 50 таких блоков

for (var i = 0; i < 51; i++){   
 document.body.appendChild(createCoub('coub'));
}

И дальше идём сама проблема, брал код с javascript.learn, drug & drop, получается перетаскивать только 1 квадрат, который стоит первый в списке, пробовал перебирать их всех циклом и подставлять, но выдаёт ошибку, мол не может найти div[i].

function drag(){
    var div = document.querySelector('.coub');    


div.onmousedown = function(e) { 

  moveAt(e);

  div.style.zIndex = 1000; 

  function moveAt(e) {
    div.style.left = e.pageX - div.offsetWidth / 2 + 'px';
    div.style.top = e.pageY - div.offsetHeight / 2 + 'px';
  }

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

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

drag();
1
  • А можно добавить какой-то более менее... работающий код ?
    – NeedH8
    3 ноя 2018 в 12:41

1 ответ 1

2

Как-то так...

window.onload = function() {
  var oActive, aDivs;
  var oCheckbox = document.querySelector('input[type="checkbox"]');

  function createCoub(className, t) {
    let div = document.createElement('div');
    div.className = className;
    div.style.width = '20px';
    div.style.height = '20px';
    div.style.backgroundColor = 'hsla(' + Math.floor(Math.random() * 300 - 1) + ',100%,50%,.8)';
    div.style.border = '1px solid #000';
    div.style.margin = '0px';
    div.style.position = 'absolute';
    div.style.top = Math.floor(Math.random() * (300 - 0)) + 0 + 'px';
    div.style.left = Math.floor(Math.random() * (400 - 0)) + 0 + 'px';
    div.draggable = true;
    div.id = t;
    return div;
  }

  for (var i = 0; i < 51; i++) {
    document.body.appendChild(createCoub('coub', i));
  }

  function moveAt(e, obj) {
    let nShiftX = parseInt(obj.style.left) - e.pageX;
    let nShiftY = parseInt(obj.style.top) - e.pageY;

    if (oCheckbox.checked) {
      aDivs.forEach(function(item) {
        item.style.left = parseInt(item.style.left) - nShiftX - item.offsetWidth / 2 + 'px';
        item.style.top = parseInt(item.style.top) - nShiftY - item.offsetHeight / 2 + 'px';
      });
    } else {
      obj.style.left = parseInt(obj.style.left) - nShiftX - obj.offsetWidth / 2 + 'px';
      obj.style.top = parseInt(obj.style.top) - nShiftY - obj.offsetHeight / 2 + 'px';
    }
  }

  function drag() {
    aDivs = document.querySelectorAll('.coub');
    aDivs.forEach(function(item) {
      item.onmousedown = function(e) {
        oActive = this;
        moveAt(e, oActive);
        oActive.style.zIndex = 1000;
        oActive.ondragstart = function(e) {
          return false
        }
        document.onmousemove = function(e) {
          moveAt(e, oActive);
        }
        document.onmouseup = function() {
          document.onmousemove = null;
          document.onmouseup = null;
        }
      }
    });
  }

  drag();
}
<label><input type="checkbox">Все<label>

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими пользовательским соглашением, политикой конфиденциальности и политикой о куки

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