有没有办法检测我是否在文本上空盘旋?

我真正想要的是检测光标何时变为“文本”类型,也就是说,当我将鼠标hover在一段文本上时。 我曾尝试查看我hover的元素类型,但这不太准确,因为我不知道它们实际包含的内容。

我知道只有先前由我分配了CSS光标属性才能检测到它。

这有可能吗? 你会怎么做呢?

编辑:我不想检查如果我当前在特定元素上,我想知道我是否将鼠标hover在该元素中的任何文本上。 div可以是浏览器的100%宽度,但是在最左边有一段较短的文本。 我不想检测何时将鼠标hover在元素的任何部分上。

无需尝试检测光标是否更改。

您可以使用这种结构简单地检测鼠标是否hover您的文本:

document.getElementById('myTextId').onmouseover = function() { // do something like for example change the class of a div to change its color : document.getElementById('myDivId').className = 'otherColor'; }; 

如果您没有id但只有类或标记,则可以用getElementsByClassName或getElementByTagName替换getElementById(它将返回您将迭代的数组)。

如果你想在离开元素时恢复颜色,我建议你以相同的方式绑定事件onmouseout。

例如,如果您想对任何段落执行某些操作,您可以这样做:

 var paras = document.getElementByClassName('p'); for (var i=0; i 

我打算做很多像这样的事情,我建议你看一下jquery及其教程。

如果您正在使用jQuery(您应该使用jQuery,因为jQuery非常棒),请执行以下操作:

 $("#myDiv").mouseover(function() { $("#myDiv").css("background-color", "#FF0000"); }); 

一种可能的方法是找到DOM中的所有文本节点,并将它们包含在具有特定类的范围中。 然后你可以选择那个类并随意做任何事情:

 // Wrap all text nodes in span tags with the class textNode (function findTextNodes(current, callback) { for(var i = current.childNodes.length; i--;){ var child = current.childNodes[i]; if(3 === child.nodeType) callback(child); findTextNodes(child, callback); } })(document.body, function(textNode){ // This callback musn't change the number of child nodes that the parent has. This one is safe: $(textNode).replaceWith('' + textNode.nodeValue + ''); }); // Do something on hover on those span tags $('.textNode').hover(function(){ // Do whatever you want here $(this).css('color', '#F00'); },function(){ // And here $(this).css('color', '#000'); }); 

JSFiddle演示

显然,这会为你的DOM填充很多span标签,而你只想在页面加载时执行一次,因为如果你再次运行它会使跨度的数量增加一倍。 如果您已经将自定义css应用于跨度,这也可能会发生奇怪的事情。