简体   繁体   中英

How to make div follow mouse when being dragged

I'm creating a little webpage for a client of mine on Fiverr. He wants a drag and dropbox that when you drag the image the drag icon (the image the mouse holds on to while dragging something) goes bigger and the opacity changes. I've already done this but when I Drag the picture around it is very slow. Please help me with this because I'm new to javascript and I don't know what to do.

Index.html

<div draggable="true">
<section class="boxes first">
    <div draggable="true">
        <img
            src="https://www.w3schools.com/images/compatible_opera.png"
        />
    </div>
    <div draggable="true">
        <img
            src="https://www.w3schools.com/images/compatible_safari.png"
            alt=""
        />
    </div>
    <div draggable="true">
        <img
            src="https://www.w3schools.com/images/compatible_firefox.png"
            alt=""
        />
    </div>
    <div draggable="true">
        <img
            src="https://www.w3schools.com/images/compatible_edge.png"
            alt=""
        />
    </div>
    <div draggable="true">
        <img
            src="https://www.w3schools.com/images/compatible_chrome.png"
            alt=""
        />
    </div>
</section>

<section class="boxes second" style="margin-top: 5em">
    <div draggable="true">Drag to here</div>
    <div draggable="true">Drag to here</div>
    <div draggable="true">Drag to here</div>
    <div draggable="true">Drag to here</div>
    <div draggable="true">Drag to here</div>
</section>
</div>

<style>
    * {
    box-sizing: border-box;
}
body {
    counter-reset: header;
}
.boxes {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    width: 100%;
    background-color: #99c5ff;
    padding: 2em;
}
.boxes > div img {
    width: 50px;
    height: 50px;
}
.boxes > div {
    width: 150px;
    height: 150px;
    transition: opacity 300ms ease-out, transform 300ms ease-out;
}
.boxes.second > div {
    background: #b7c1fe;
}
.boxes > div.drag {
    opacity: 0;
}
.boxes > div.over {
    border: 2px dashed #222;
}

.dragging img {
  display: none;
}

/* [draggable] {
} */
[draggable] {
    transition: 0.3s;
    user-select: none;
    /* Required to make elements draggable in old WebKit */
    -khtml-user-drag: element;
    -webkit-user-drag: element;
}

</style>

<script>

const draggables = document.querySelectorAll('[draggable="true"]');

console.log(draggables);

draggables.forEach((draggable) => {
    draggable.addEventListener("dragstart", () => {
        draggable.classList.add("dragging");
    });
});
draggables.forEach((draggable) => {
    draggable.addEventListener("dragend", () => {
        draggable.classList.remove("dragging");
    });
});

let dragSrcEl = null;

function logEventData(origin, e) {
    console.log(`Event Origin: ${origin}`);
    console.log(`Event Type: ${e.type}`);
    console.log(e);
    console.log("---------------");
}

function dragStart(e) {
    e.dataTransfer.setDragImage(new Image(), 0, 0) //5000 will be out of the window
    drag(e)
    logEventData("dragStart", e);

    this.classList.add("drag");
    dragSrcEl = this;
    e.dataTransfer.effectAllowed = "move";
    e.dataTransfer.setData("text/html", this.innerHTML);
}


var crt, dragX, dragY;
//document.addEventListener('drag',drag)
function drag(ev) {
  crt = ev.target.cloneNode(true);
  console.log(crt)
  crt.className = "face";
  crt.style.position = "absolute";
  crt.style.transform = "scale(2.5)";
  crt.style.opacity = "1";
  document.body.appendChild(crt);
  ev.dataTransfer.setData("text", ev.target.id);
}



function dragOver(e) {
    // logEventData('dragOver', e);
    
      e = e || window.event;
      dragX = e.pageX + 30;
      dragY = e.pageY + 30;
      crt.style.left = dragX + "px";
      crt.style.top = dragY + "px";
  crt.style.zIndex = 0;
      console.log("X: " + dragX + " Y: " + dragY);
    e.preventDefault();
    e.dataTransfer.dropEffect = "move";
    return false;
}

function dragEnter(e) {
    logEventData("dragEnter", e);

    this.classList.add("over");
}

function dragLeave(e) {
    logEventData("dragLeave", e);

    this.classList.remove("over");
}

function dragDrop(e) {
    logEventData("dragDrop", e);

    e.stopPropagation();

    if (dragSrcEl !== this) {
        dragSrcEl.innerHTML = this.innerHTML;
        this.innerHTML = e.dataTransfer.getData("text/html");
    }
    return false;
}

function dragEnd(e) {
  crt.style.display = 'none';
  crt.remove()
    logEventData("dragEnd", e);

    [].forEach.call(boxes, (box) => {
        box.classList.remove("over");
        box.classList.remove("drag");
    });
}

const boxes = document.querySelectorAll(".boxes > div");
[].forEach.call(boxes, (box) => {
    box.addEventListener("dragstart", dragStart, true);
    box.addEventListener("dragenter", dragEnter, true);
    box.addEventListener("dragover", dragOver, true);
    box.addEventListener("dragleave", dragLeave, true);
    box.addEventListener("drop", dragDrop, true);
    box.addEventListener("dragend", dragEnd, true);
});



</script>

This may help you, adapt it to your code.

 const fill = document.querySelector(".fill"); const empties = document.querySelectorAll(".empty"); // Listeners fill.addEventListener("dragstart", dragStart); fill.addEventListener("dragend", dragEnd); // Add listeners to empty boxes for (const empty of empties) { empty.addEventListener("dragover", dragOver); empty.addEventListener("dragenter", dragEnter); empty.addEventListener("dragleave", dragLeave); empty.addEventListener("drop", dragDrop); } // Drag Functions function dragStart() { this.className += " hold"; setTimeout(() => (this.className = "invisible"), 0); } function dragEnd() { this.className = "fill"; } function dragOver(e) { e.preventDefault(); } function dragEnter(e) { this.className += " hovered"; } function dragLeave() { this.className = "empty"; } function dragDrop() { this.className = "empty"; this.append(fill); }
 .fill { background-image: url("https://source.unsplash.com/random/150x150"); position: relative; height: 150px; width: 150px; top: 5px; left: 5px; cursor: pointer; }.hold { border: 5px solid #ccc; height: 200px; width: 200px; }.empty { display: inline-block; height: 160px; width: 160px; margin: 10px; border: solid 4px blue; background: white; }.hovered { background: #f4f4f6; border: solid 4px red; }
 <,DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width. initial-scale=1.0" /> <title>Drag and drop</title> <link rel="stylesheet" href="style.css" /> </head> <body> <div class="empty"> <div class="fill" draggable="true"></div> </div> <div class="empty"></div> <div class="empty"></div> <script src="js.js"></script> </body> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM