[英]Detect mouse cursor type
我想要 JavaScript 代码来检测鼠标 cursor 类型。
例如,当 cursor 悬停在<textarea>
中时,它会从默认更改为文本。
我将如何 go 检测到这个?
你可以做到这一点,但它不漂亮,可能会很慢,这取决于你页面上有多少元素。
$('*').mouseenter(function(){
var currentCursor = $(this).css('cursor') ;
//do what you want here, i.e.
console.log( currentCursor );
});
您可以使用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);
};
我有一个很好的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
});
正如这里所建议的,使用getComputedStyle
对我有用。
const onMouseOver = function (e) {
var cursor = getComputedStyle(e.target).cursor;
console.log({ cursor });
};
document.addEventListener("mouseover", onMouseOver, false);
虽然当 cursor 设置为自动时,这无助于检测准确的 cursor 类型,但我们至少可以在 cursor 设置为非自动时使用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.