有没有办法检测我是否将鼠标悬停在文本上

Is there a way to detect if I'm hovering over text?

本文关键字:悬停 鼠标 文本 是否 检测 有没有      更新时间:2023-09-26

我真正想要的是检测光标何时变为键入"文本",即当我将鼠标悬停在一段文本上时。我尝试查看我悬停在上面的元素类型,但这不太准确,因为我不知道它们实际包含什么。

我知道检测 CSS 光标属性只有在我之前分配的情况下才有可能。

这可能吗?你会怎么做?

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

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

您可以使用这种结构简单地检测鼠标是否悬停在文本上:

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<paras.length; i++) {
    paras[i].onmouseover = function() {
        // do something like for example change the class of a div to change its color :
        document.getElementById('myDivId').className = 'otherColor';
    };
}

我打算做很多这样的事情,我建议你看看jquery和它的教程。

一种可能的方法是找到 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('<span class="textNode">' + textNode.nodeValue + '</span>');
});
// 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 Demo

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

这个对另一个问题的回答给出了一个从点获取节点的函数。使用它,您可以检查鼠标是否在文本节点的边界框上。

function isPointOverText(x, y) {
    const element = document.elementFromPoint(x, y);
    if (element == null) return false;
    const nodes = element.childNodes;
    for (let i = 0, node; (node = nodes[i++]); ) {
        if (node.nodeType === 3) {
            const range = document.createRange();
            range.selectNode(node);
            const rects = range.getClientRects();
            for (let j = 0, rect; (rect = rects[j++]); ) {
                if (
                    x > rect.left &&
                    x < rect.right &&
                    y > rect.top &&
                    y < rect.bottom
                ) {
                    if (node.nodeType === Node.TEXT_NODE) return true;
                }
            }
        }
    }
    return false;
}
window.addEventListener("mousemove", (e) => {
    console.log(isPointOverText(e.clientX, e.clientY))
})

如果你使用的是jQuery(你应该这样做,因为jQuery很棒),请这样做:

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