0

Poseo estas cuatro funciones que permiten arrastrar un objeto del DOM:

function addListeners(elemento) {
    elemento.addEventListener('mousedown', mouseDown, false);
    window.addEventListener('mouseup', mouseUp, false);
}

function mouseUp() {
    window.removeEventListener('mousemove', divMove, true);
 }

function mouseDown(e) {
  window.addEventListener('mousemove', divMove, true);

}

function divMove(e) {
    // Recien agrego e.target.
    // Anteriormente estaba asi =>
    // let elemento = document.getElementById("div");
    // Pues era un único div
    elemento = e.target;
    elemento.style.position = 'absolute';
    elemento.style.top = e.clientY + 'px';
    elemento.style.left = e.clientX + 'px';
}

Con esta funcion creo los tipos de elementos (cajas, textareas y demas):

function crearCaraja() {
    let caja = document.createElement("input");
                    caja.setAttribute('placeholder', 'Caja '+numeroCajas);
                    caja.setAttribute("id","caja"+numeroCajas);
                designLayer.append(caja);
                actualizarTabla("caja");
                caja.focus();
                addListeners(caja);
}

Quisiera que a cada elemento al ser creado se le agregara las funciones de moveUp, moveDown y divMove.

En un principio funcionan bien las dos primeras, pero divMove daba error porque no estaba definido elemento, lo que hice fue agregar e.target, pero cuando le doy para arrastrar el elemento arrastrara completamente todo el div principal.

¿Como puedo modificar la función para que se le agregue los eventos a cada elemento creado?

HTML:

<body>
<div id="designDiv">

</div>

<button onclick="crearElemento('caja')">Crear Caja</button>
</body>

let numeroCajas = 0;

const infoTableCaja =  document.getElementById("filasCajas");

let arrayCaja = [];

const designLayer = document.getElementById("designDiv");

function crearElemento(tipo) {
    switch(tipo) {
        case "caja":
        numeroCajas++;
            let caja = document.createElement("input");
                caja.setAttribute('placeholder', 'Caja '+numeroCajas);
                caja.setAttribute("id","caja"+numeroCajas);
            designLayer.append(caja);
            caja.focus();
            arrayCaja.push(caja.id);
            addListeners(caja);
        break;
    }
}


function addListeners(elemento) {
    elemento.addEventListener('mousedown', mouseDown, false);
    window.addEventListener('mouseup', mouseUp, false);
}

function mouseUp() {
    window.removeEventListener('mousemove', divMove, true);
 }

function mouseDown(e) {
  window.addEventListener('mousemove', divMove, true);

}

function divMove(e) {
    if(arrayCaja.indexOf(e.id)) {
        elemento = e.target;
        elemento.style.position = 'absolute';
        elemento.style.top = e.clientY + 'px';
        elemento.style.left = e.clientX + 'px';
    }
}
2
  • Puedes añadir un ejemplo de tu HTML? no me queda claro cómo están organizados tus inputs y divs el 4 sep. 2017 a las 13:47
  • @PabloLozano agregare lo que tengo realizado
    – Dev 200
    el 4 sep. 2017 a las 13:55

2 respuestas 2

1

Puedes hacerlo de varias formas, una forma es usando delegación de eventos, como lo haces actualmente, otra forma es añadiendo los listeners y removiendo los listeners directamente sobre los elementos.

Ejemplo

let numeroCajas = 0;
let numeroEnlaces = 0;
let numeroRellenos = 0;
const arrayCaja = [];

// NODES
const infoTableCaja = document.getElementById("filasCajas");
const infoTableEnlace = document.getElementById("filasEnlaces");
const infoTableRelleno = document.getElementById("filasRellenos");
const designLayer = document.getElementById("designDiv");

const crearElemento = (tipo) => {
  switch (tipo) {
    case "lista":
      let lista = document.createElement("li");
      lista.innerHTML = "Caja" + numeroCajas;
      return lista;

    case "caja":
      numeroCajas++;
      let caja = document.createElement("input");
      caja.setAttribute('placeholder', 'Caja ' + numeroCajas);
      caja.setAttribute("id", "caja" + numeroCajas);
      designLayer.append(caja);
      actualizarTabla("caja");
      caja.focus();
      arrayCaja.push({ id: caja.id });
      addListeners(caja);
      break;

    case "enlace":
      break;

    case "relleno":
      let relleno = document.createElement("textarea");
      relleno.setAttribute("rows", "5");
      relleno.setAttribute("cols", "20");
      designLayer.append(relleno);
      actualizarTabla("relleno");
      relleno.focus();
      break;
  }
};

const actualizarTabla = (elemento) => {
  switch (elemento) {
    case "caja":
      let listaCaja = crearElemento("lista");
      infoTableCaja.append(listaCaja);
      break;
    case "enlace":
      let listaEnlace = crearElemento("lista");
      infoTableEnlace.append(listaEnlace);
      break;
    case "relleno":
      let listaRelleno = crearElemento("lista");
      infoTableRelleno.append(listaRelleno);
      break;
  }
};


function addListeners(el) {
  el.addEventListener('mouseup', mouseUp);
  el.addEventListener('mousedown', mouseDown);
}

function mouseDown(e) {
  const el = e.target;
  el.style.position = 'absolute';
  const offset = arrayCaja.find(c => c.id === el.id);
  offset.y = el.offsetTop - e.clientY;
  offset.x = el.offsetLeft - e.clientX;
  el.addEventListener('mousemove', divMove);
}

function mouseUp(e) {
  e.target.removeEventListener('mousemove', divMove);
}

function divMove(e) {
  const el = e.target;
  const offset = arrayCaja.find(c => c.id === el.id);
  el.style.top = `${offset.y + e.clientY}px`;
  el.style.left = `${offset.x + e.clientX}px`;
}
*,
*:before,
*:after {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}
body {
  background-color: #fff;
  font-family: 'Segoe UI', 'Ubuntu', 'Noto Sans', sans-serif;
  padding: 15px;
}
h3 {
  color: #333;
  font-size: 22px;
  font-weight: lighter;
  margin: 20px 0;
  text-align: center;
}
table {
  border-collapse: collapse;
  width: 100%;
}
table thead {
  background-color: #f9f9f9;
  border-bottom: 2px solid #ddd;
}
table thead th {
  color: #555;
  font-size: 13px;
  font-weight: bold;
  padding: 8px 15px;
  text-align: center;
  text-transform: uppercase;
}
table tbody td {
  padding: 8px 15px;
}
#actions {
  margin: 20px 0;
  text-align: center;
}
#actions button {
  background-color: #eee;
  border: none;
  border-radius: 3px;
  color: #555;
  font-size: 14px;
  padding: 8px 10px;
}
#actions button:first-child {
  background-color: #2980b9;
  color: #fff;
}
#actions button:nth-child(2) {
  background-color: #27ae60;
  color: #fff;
}
#actions button:last-child {
  background-color: #f39c12;
  color: #fff;
}
li {
  color: #333;
  list-style: none;
}
li::before {
  background: url('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTffz08uHyfXBMRzg63FLRd3dENXSu6QQLXn5h_lfJx4csGSGJ_UA') no-repeat;
  background-size: 10px 10px;
  content: "";
  margin-right: 8px;
  padding-right: 10px;
  vertical-align: sub;
}
input {
  border: 1px solid #ddd;
  border-radius: 3px;
  color: #333;
  font-size: 14px;
  padding: 8px;
}
<div id="infoDiv">
  <h3>Información</h3>
  <table id="infoTable">
    <thead>
      <tr>
        <th>Cajas</th>
        <th>Enlaces</th>
        <th>Rellenos</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td id="filasCajas">
        </td>
        <td id="filasEnlaces">
        </td>
        <td id="filasRellenos">
        </td>
      </tr>
    </tbody>
  </table>
</div>

<div id="designDiv">

</div>

<div id="actions">
  <button onclick="crearElemento('caja')">Crear Caja</button>
  <button onclick="crearElemento('enlace')">Crear Enlace</button>
  <button onclick="crearElemento('relleno')">Crear Relleno</button>
</div>

Si usas delegación de eventos, deberás buscar en arrayCaja si existe algún objeto con el id del target:

const target = e.target;
const targetId = target.id;
const targetData = arrayCaja.find(c => c.id === targetId);

if (targetData) {
  // el evento se ha producido sobre una caja
}
0

Aquí tienes un fallo: Array.indexOf te devuelve -1 si no encuentra el elemento, lo que hace que el contenido de la condición se ejecute siempre que el elemento no esté en la primera posición del array (la única vez que se devuelve 0 y, por tanto, la condición es falsa.

function divMove(e) {
    if(arrayCaja.indexOf(e.id)) {
        elemento = e.target;
        elemento.style.position = 'absolute';
        elemento.style.top = e.clientY + 'px';
        elemento.style.left = e.clientX + 'px';
    }
}
1
  • Mueve todo el div, no solo el elemento creado.
    – Dev 200
    el 4 sep. 2017 a las 13:37

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.