【问题标题】:How to change cursor based on mouse position?如何根据鼠标位置更改光标?
【发布时间】:2010-07-12 13:11:27
【问题描述】:

当鼠标进入body元素的矩形(50、50、100、100)(数字以像素为单位)时,我想将光标从default更改为pointer

我知道我可以定义一个div,把它放在这个位置,然后在上面设置cursor: pointer;,但是我正在寻找一些不定义div的方法。

我想要类似的东西:

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

这样可以吗?

【问题讨论】:

  • 在 mousemove 上更改容器的光标。

标签: javascript jquery html css cursor


【解决方案1】:

尝试这样的事情(虽然未经测试):

$("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");
});

出于性能原因,您可能希望使用全局变量,而不是每次都应用属性。您可能还想研究使用 CSS 类而不是直接在 JS 中设置样式。

更新:为什么我认为style 而不是css... :(

【讨论】:

  • 而不是 .style("cursor", "default") 我通常使用 .style("cursor", "") 以防页面上实际未使用“默认”光标。
  • .style() won't work, regardless how you try to call it, because it's no jQuery method. You are looking for .css()`
  • 您应该在此处使用.css() 而不是.style(),尽管它不能确保这将起作用。例如,如果您在一个定义了光标的元素之上,那是一种比 &lt;body&gt; 更本地化的样式......但这应该足够好。
  • 我的主要问题是&lt;input type='file' /&gt; 元素,它强制光标是别的东西。见这里:jsfiddle.net/rdnhh/1。任何解决方法的想法?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-16
  • 1970-01-01
相关资源
最近更新 更多