简体   繁体   中英

Applying CSS styles not behaving correctly with Javascript

I am working with a canvas that spans the entire width and length of a webpage. I can create boxes whenever I click down anywhere on the canvas, move my mouse in any direction, and once I release the box is created. Think of how selection works in any desktop, but on mouseup the selection box is drawn on the canvas.

My problem is that I want to update the cursor whenever I mouseover any of the boxes I created. I am storing them inside an array called panels.

function mouseOverPanels(e) {
        var mouseX = e.clientX, mouseY = e.clientY;

        // loop through all the panels
        for (var i = 0; i < panels.length; i++) {
            // if cursor is within the bounds of one of the panels, update cursor
            if ((mouseX >= panels[i].x && mouseX <= panels[i].x + panels[i].width) && (mouseY >= panels[i].y && mouseY <= panels[i].y + panels[i].height)) {
                canvas.style.cursor = "pointer";
            }

            // if not, then set the cursor to "crosshair" (default)
            else canvas.style.cursor = "crosshair";
        }
    }

This code is working. When I first create a panel, if I mouse over it, it registers correctly that the cursor is within its bounds and updates the cursor accordingly. However, whenever I create new panels, this function stops updating the cursor for all the previous ones and only works for the latest panel created, even though it registers correctly whenever I mouse over the previous panels, it just doesn't update the cursor within their bounds.

Thoughts? Solution must be implemented entirely with javascript, without the use of libraries.

It's because your if/else will happen on each loop , so only the result of the final loop ends up being relevant, as though you didn't have a loop at all and just used panels[panels.length - 1] .

Instead, set a default and then set the pointer when you find a relevant entry (and stop looping):

// loop through all the panels
var cursor = "crosshair";
for (var i = 0; i < panels.length; i++) {
    // if cursor is within the bounds of one of the panels, update cursor
    if ((mouseX >= panels[i].x && mouseX <= panels[i].x + panels[i].width) && (mouseY >= panels[i].y && mouseY <= panels[i].y + panels[i].height)) {
        cursor = "pointer";
        break;
    }
}
canvas.style.cursor = cursor;

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