检测游标类型
我想要JavaScript代码来检测游标类型。
例如,当光标hover在textarea中时,它会从默认值更改为文本。
你可以这样做,但它不漂亮,可能会很慢,具体取决于你页面上有多少元素。
$('*').mouseenter(function(){ var currentCursor = $(this).css('cursor') ; //do what you want here, ie console.log( currentCursor ); });
您可以使用JavaScript检测游标类型
喜欢
并且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,只需将其更改为
JavaScript应该看起来像这样
function detect_cursor() { alert("test"); var ctl = document.getElementById('sample_text'); var startPos = ctl.selectionStart; var endPos = ctl.selectionEnd; alert(startPos + ", " + endPos); };
我有一个很好的jQuery扩展,非常适合这种类型的东西:
要使用它,只需执行以下操作:
$("#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
我认为您可以像设置它一样读取cursor
css属性,但是您必须从特定元素执行此操作,因为AFAIK无法从窗口或文档对象中读取光标类型。 遵循此逻辑,要获取当前游标类型,您必须找到鼠标所在的当前元素并读取其cursor
css。 但是,您必须经常检查光标是否发生变化,这很慢并且容易出错(通常您应该尝试将代码放在事件处理程序中以对某些事情作出反应,而不是经常检查是否它发生了,并将您的代码放在该函数中,它更符合逻辑,更高效,更强大,更清晰。)
但是检测光标类型的想法仍然让我着迷,如果有人知道我喜欢听到它。 :d
作为一种替代解决方案,为什么不设置一个事件处理程序,当它进入一个会改变它的元素时,而不是读取游标类型? 这样会更容易出错并且可能更直接,因为我不认为你太关心光标,但是如果鼠标已输入特定元素。
$("#textbox").mouseover( function() { //I know the cursor has changed because it is now in a textbox });