检测游标类型

时间:2011-03-14 21:18:39

标签: javascript jquery css cursor

我想要JavaScript代码来检测游标类型。

例如,当光标悬停在textarea中时,它会从默认值更改为文本..

4 个答案:

答案 0 :(得分:3)

你可以做到这一点,但它并不漂亮,而且可能会很慢,具体取决于你页面上有多少元素。

$('*').mouseenter(function(){
    var currentCursor = $(this).css('cursor') ;

    //do what you want here, i.e.
    console.log( currentCursor );
});

答案 1 :(得分:2)

您可以使用JavaScript

检测光标类型

<input id="sample_text" name="one" type="text" value="Sample Text" />

,JavaScript代码看起来应该是这样的

$('input[id=sample_text]').click( function() {
   alert("test");   
   var ctl = document.getElementById('sample_text');
   var startPos = ctl.selectionStart;
   var endPos = ctl.selectionEnd;
   alert(startPos + ", " + endPos);
});

您还可以查看此Jsfiddle for Js Cursor Detection

以上是编写的Jquery代码,您也可以使用Vanilla JS,只需将其更改为

<input id="sample_text" name="one" type="text" value="Sample Text" onclick="detect_cursor()" />

并且JavaScript应该看起来像这样

function detect_cursor() {
   alert("test");   
   var ctl = document.getElementById('sample_text');
   var startPos = ctl.selectionStart;
   var endPos = ctl.selectionEnd;
   alert(startPos + ", " + endPos);
};

答案 2 :(得分:1)

我有一个很好的jQuery扩展,非常适合这种类型的东西:

  

https://gist.github.com/2206057

要使用它,请执行以下操作:

$("#eleID").cursor(); // will return current cursor state for that element
$("#eleID").cursor("pointer"); // will change ele cursor to whatever is ""
$("#eleID").cursor("clear"); // will change ele cursor to default
$("#eleID").cursor("ishover"); // will return boolean of if mouse is over element or not
$("#eleID").cursor("position"); // will return cursor's current position in "relation" to element

$.cursor("wait") // will change document cursor to whatever is ""
$.cursor($("#eleID"), "wait"); // same as $("#eleID").cursor("wait");
$.cursor("position") // will return current cursor position

还应该提一下,如果您为“position”和“isHover”提交了多个元素,例如$("#eleID1, .elementsWiththisClass"),那么它将返回包含以下对象的Array

var poses = $("#eleID1, .elementsWiththisClass").cursor("position") //  will equal
poses[0] = {
    ele: e.fn.e.init[1], // the jquery element
    x: XXX, //  where XXX is the cursors current position in relation to element
    y: XXX
}
poses[1] = { // ...and so on and so forth for each element

答案 3 :(得分:0)

我认为您可以像设置它一样阅读cursor css属性,但是您必须从特定元素执行此操作,因为AFAIK无法从窗口或文档对象中读取游标类型。遵循这个逻辑,要获取当前游标类型,您必须找到鼠标所在的当前元素并读取其cursor css。但是,您必须经常检查光标是否发生了变化,这很慢并且容易出错(通常您应该尝试将代码放在事件处理程序中以对某些事情作出反应,而不是经常检查是否它发生了,并将你的代码放在该函数中,它更符合逻辑,更高效,更健壮,更清晰。)

但是检测光标类型的想法仍然让我着迷,如果有人知道我喜欢听到它。 :d


作为一种替代解决方案,为什么不设置一个事件处理程序,以便它进入一个可以改变它的元素,而不是读取游标类型?这样会更容易出错并且可能更直接,因为我认为你不关心光标,但是如果鼠标已输入特定元素。

$("#textbox").mouseover( function() { 
    //I know the cursor has changed because it is now in a textbox
});