简体   繁体   中英

How to change cursor based on mouse position?

I would like to change the cursor from default to pointer when the mouse enter the rectangle (50, 50, 100, 100) of the body element (the numbers are in pixels).

I know that I could define a div , place it at this position, and set cursor: pointer; on it, but I'm looking for some way without defining a div .

I would like to something like:

if (mousePosition inside rectangle) {
    change cursor to pointer
} else {
    change cursor to default
}

Is that possible to do that ?

Try something like this (untested though):

$("body").mousemove(function(e){
    if (e.pageX > 50 && e.pageY > 50 && e.pageX < 100 && e.pageY < 100)
        $("body").css("cursor", "pointer");
    else
        $("body").css("cursor", "default");
});

You might want to use a global variable though instead of just appling the properties each time for performance reasons. You also might want to look into using CSS classes instead of directly setting the style in JS.

Update: Why did I think style instead of css ... :(

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