简体   繁体   中英

Change background on hover of a draggable div

I have a small draggable division (black) and many nodes with different IDs beside it

在此处输入图片说明

I need a hovering effect when I drag the black element on the nodes. What I am doing in allowDrop function is:

var dragObj;

function drag(ev){
    dragObj = ev;
}


function allowDrop(ev){
    ev.preventDefault();
    var Dragged = dragObj;
    var Hovered = ev;
    var leftIndent = Dragged.layerX;
    var hoveredID = Hovered.target.id.toString().split('_');
    var nodesOnLeft = Math.floor(leftIndent/12);
    var startingNode = hoveredID[0]-nodesOnLeft;
    for (i=1;i<=Math.floor(draggableElementLength/12);i++){
        var toApplyCssID = startingNode.toString() + '_1';
        var toApplyCss = document.getElementById(toApplyCssID);
        $('#'+toApplyCssID).css('background-color','lightgreen');
    }
}

basically I am using the layerX property to find out the distance between my mouse pointer and draggable division's border and adjusting that to calculate number of nodes where I have to apply new CSS and applying that by finding the ID of node.

This is working but its making the process very slow as it involves many calculations and its not the hover effect as its not going away when I am removing the draggable division.

Is there any other way to achieve this or do I need to make code changes in existing code.

thanks

Without the HTML and the rest of the script, I can only point you in the direction you should be taking in this kind of scenario:

Don't constantly repeat calculations (that do not change) in a loop, store them outside the function:

  • Use document.getElementById(toApplyCssID) for each node and store the elements in an array
  • Get the distance from the mouse position to the required edge or edges of the div (leftIndent) on initial drag/mousedown and store that in a variable
  • Store Math.floor(draggableElementLength/12) in another variable (you haven't shown where this originates, but it doesn't seem to change in the function...)
  • Apply the CSS to the relavent elements (from the array of elements) using the other stored values to select them
  • Remove the CSS on those that had it applied earlier

This may not be the ultimate solution, but these are some of the things you can look at to speed up what you (may) have currently.

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