简体   繁体   English

如何根据鼠标位置更改光标?

[英]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). 当鼠标进入body元素的矩形(50,50,100,100)时(数字以像素为单位),我想将光标从default更改为pointer

I know that I could define a div , place it at this position, and set cursor: pointer; 我知道我可以定义一个div ,将它放在这个位置,并设置cursor: pointer; on it, but I'm looking for some way without defining a div . 在它上面,但我正在寻找一些没有定义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. 您也可能希望使用CSS类而不是直接在JS中设置样式。

Update: Why did I think style instead of css ... :( 更新:为什么我认为style而不是css ...... :(

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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