1

Есть блок, который можно перетаскивать мышкой, и код работает, если использовать id и document.getElementById. Но на сайте блоки будут добавляться в неограниченном количестве. Как сделать так, чтобы все блоки с одним классом перетаскивались мышкой?

   var card = document.getElementById('card');


    card.onmousedown = function(e) {

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

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

      card.style.zIndex = 1000;

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

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

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

    }

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


    function getCoords(elem) {
      var box = elem.getBoundingClientRect();

      return {
        top: box.top + pageYOffset,
        left: box.left + pageXOffset
      };

    }
    
    
body .card {
  position: relative;
  height: 12rem;
  width: 10%;
  min-width: 200px;
  box-shadow: 0 0 2rem -1rem rgba(0, 0, 0, 0.05);
  display: inline-block;
  z-index: 99999999!important;
  margin: 10%;
}
body .card .cardcontainer {
  position: absolute;
  width: 100%;
  height: 100%;
  border-radius: 1rem;
  background: var(--background);
  color: var(--text);
}
.schema2 {
  display: none;
}
<div class='col-6' id="card">
  <span class="in-kod">
    <div class="card purple center">
      
      <div class="cardcontainer">  
        <textarea class="arguments"></textarea> 
      </div>
    </div>
  </span>
</div>
<div class='col-6' id="card">
  <span class="in-kod">
    <div class="card purple center">
      
      <div class="cardcontainer">  
        <textarea class="arguments"></textarea> 
      </div>
    </div>
  </span>
</div>

0

1 ответ 1

4

document.querySelectorAll('.movable').forEach((el,i) =>
  el.style.left = `${i*100+30}px`
);

document.querySelectorAll('.movable').forEach(el =>
  el.onmousedown = e => 
    e.target.onmousemove = e => 
      Object.assign(e.target.style,{
        top: `${e.target.offsetTop + e.movementY}px`,
        left: `${e.target.offsetLeft + e.movementX}px`
      })
);

window.onmouseup = window.onblur = e =>
  document.querySelectorAll('.movable').forEach(el => {
    el.onmousemove = null;
  });
.movable {
  width: 60px;
  height: 60px;
  display: block;
  background: red;
  position: absolute;
  top: 30%;
}
<span class="movable"></span>
<span class="movable"></span>
<span class="movable"></span>
<span class="movable"></span>
<span class="movable"></span>
<span class="movable"></span>

И второй вариант может быть таким.

Можно добавлять любые элементы, если у них есть класс movable, они будут двигаться без объявления каких-либо событий.

const count = 300;

const gencol = (a) => `#${(Math.trunc(Math.random()*0x1000)).toString(16).padStart(3,0)}${a}`;

for(let i = 0; i < count; i++ ){
  const span = document.createElement('span');
  span.className = i%3 ? 'movable' : 'static';
  Object.assign(span.style,{
    top: `${~~(i/20)*40}px`,
    left: `${(i%20)*40}px`,
    zIndex: i,
    backgroundColor: i%3 ? gencol('b') : 'red',
    color: i%3 ? gencol('4') : '#fff',
    cursor: i%3 ? 'move' : 'no-drop'
  });
  span.innerHTML = i%3 ? '☯' : '⊗';
  document.body.appendChild(span);
}

let movable = null;

window.onmousedown = e => {
  if(e.target && e.target.classList.contains('movable')) {
    movable = e.target;
    document.querySelectorAll('span').forEach(el => el.style.zIndex--);
    movable.style.zIndex = count;
  }
};

window.onmousemove = e => {
  if(movable){
    Object.assign(movable.style,{
      top: `${movable.offsetTop + e.movementY}px`,
      left: `${movable.offsetLeft + e.movementX}px`
    });
  }
}

window.onmouseup = window.onblur = e =>
  movable = null;
  
window.ondragstart = e => e.preventDefault();
body{
  overflow: hidden;
}

.movable {
  border: 1px solid #000;
  cursor: move;
  line-height: 33px;
}

.movable:hover{
  box-shadow: 0 0 5px 2px #00F;
  border: 1px solid #fff;
}

.static {
  border: 2px solid #F00;
/*  pointer-events: none; */
  line-height: 30px;
  cursor: no-drop;
}

.static, .movable {
  width: 30px;
  height: 30px;
  display: block;
  position: absolute;
  font-size: 30px;
  text-align: center;

  -webkit-touch-callout: none; /* iOS Safari */
    -webkit-user-select: none; /* Safari */
     -khtml-user-select: none; /* Konqueror HTML */
       -moz-user-select: none; /* Old versions of Firefox */
        -ms-user-select: none; /* Internet Explorer/Edge */
            user-select: none; /* Non-prefixed version, currently
                                  supported by Chrome, Edge, Opera and Firefox */
}

Красные клеточки не двигаются.

Ваш ответ

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

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