有没有办法检测我是否在文本上悬停? [英] Is there a way to detect if I'm hovering over text?

查看:108
本文介绍了有没有办法检测我是否在文本上悬停?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真正追求的是检测光标何时变为键入文本,也就是说,当我将光标悬停在一段文本上时。我已经尝试过查看我徘徊在的元素类型,但这不是太准确,因为我不知道它们实际包含的内容。



据我所知,检测CSS游标属性是唯一可能的,如果它以前由我分配。



这可能吗?你将如何去做这件事?



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

解决方案

不需要尝试检测游标是否改变。

您可以简单地通过使用这种构造来检测鼠标是否在您的文本上悬停:
$ b

  document.getElementById('myTextId' ).onmouseover = function(){
//做一些类似于改变div的类来改变它的颜色:
document.getElementById('myDivId')。className ='otherColor';
};

如果你没有一个id,但是一个类或一个标签,你可以用getElementsByClassName替换getElementById或getElementByTagName(它将返回您将迭代的数组)。



如果要在离开元素时恢复颜色,我建议您将事件onmouseout绑定到例如,如果你想在任何段落上做些什么,你可以这样做:



pre> var paras = document.getElementByClassName('p');
for(var i = 0; i< paras.length; i ++){
paras [i] .onmouseover = function(){
//例如更改类一个div来改变它的颜色:
document.getElementById('myDivId')。className ='otherColor';
};
}

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


What I'm really after is to detect when the cursor changes to type "text", that is, when I'm hover over a piece of text. I have tried looking at the element types I am hovering over, but this isn't too accurate because I don't know what they actually contain.

I understand that detecting the CSS cursor attribute is only possible if it has previously been assigned by me.

Is this possible at all? How would you go about doing this?

EDIT: I do not want to check If I am currently over a specific element, I want to know if I am hover over any text within that element. A div could be 100% width of the browser, but with a shorter piece of text at the far left. I don't want to detect when hovering over just any part of an element.

解决方案

No need to try to detect if the cursor changed.

You can simply detect if the mouse is hovering your text by using this kind of construct :

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';
};

If you don't have an id but a class or a tag, you can replace getElementById by getElementsByClassName or getElementByTagName (which will return arrays on which you'll iterate).

If you want to restore the color when leaving the element, I suggest you bind the event onmouseout in the same way.

For example, if you want to do something on any paragraph, you may do that :

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';
    };
}

I you plan to do a lot of things like this, I suggest you look at jquery and its tutorial.

这篇关于有没有办法检测我是否在文本上悬停?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆