简体   繁体   中英

Apply CSS to active dropped element in a drop area using JavaScript

I have few draggable nodes which need to be highlighted after drop, only the element which is dropped needs to have a border.
Eg: I drop nodeA and it will be highlighted. Later when I drop nodeB, then nodeB should be highlighted and nodeA should not be highlighted.

This is the function I have written:

function drop(ev) {
    ev.preventDefault();
    var data = ev.dataTransfer.getData("text");
    var nodeCopy = document.getElementById(data).cloneNode(true);
    test++;
    nodeCopy.id =test; /* We cannot use the same ID */
    var newNodeId= nodeCopy.id;
    ev.target.appendChild(nodeCopy);
    document.getElementById(newNodeId).className += " draggeddStyle";
}

I am able to highlight the node using:

document.getElementById(newNodeId).className += " draggeddStyle;

After that, if I drag another node, both nodes end up having the same style.

Just modifying your code sample.

function drop(ev) {
    ev.preventDefault();
    $(".draggeddStyle").removeClass("draggeddStyle");/* added this line */
    var data = ev.dataTransfer.getData("text");
    var nodeCopy = document.getElementById(data).cloneNode(true);
    test++;
    nodeCopy.id =test; /* We cannot use the same ID */
    var newNodeId= nodeCopy.id;
    ev.target.appendChild(nodeCopy);
    document.getElementById(newNodeId).className += " draggeddStyle";
}

I think this works.

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