检测选定文本上的悬停 [英] Detect hover on selected text
问题描述
当用户选择他/她的部分文本时,我想在工具提示中显示一个菜单。呈现菜单效果不错,但我只想在用户将鼠标悬停在所选文字上时显示。
如图所示:
我还没有决定定位(我喜欢它所示的方式),但要澄清,这不是问题的关键。
问题是:如何过滤发生在所选文字上的悬停事件?
问题:
-
我不能只听文本选择事件或测试悬停事件来查看它们是否在其中选择了文本。我知道如何获取选定的文本,但我不知道如何获取
解决方案 是以某种方式计算选定文本的区域并测试该区域是否发生鼠标悬停事件。 在 I can't just listen for a text selection event or test hover events to see whether they are over elements that have selected text inside them. The left image would generate a false positive with that.
I know how to get the selected text but I don't know how to get the selected region.
mouseup
上,使用 Range.getClientRects 可以获取选区每行的边界矩形。 然后,您可以测试鼠标超过了这样的选择:
var cr = [];
$ b $(文档).on({
'mouseup':function(){
cr = window.getSelection()。getRangeAt(0).getClientRects();
},
'mousemove':function(ev){
//隐藏弹出窗口
for(var i = 0; i< cr.length; i ++){$ (ev.pageX> = cr [i] .left& ev.pageX< = cr [i] .right&&
ev.pageY> = cr [i ] .top& ev.pageY< = cr [i] .bottom
){
//显示弹出窗口
break;
}
}
}
});
I am building a WYSIWYG rich text editor.
When the user selects a portion of his/her text, I would like to present a menu in a tooltip. Presenting the menu works fine but I would like to only show it if the user hovers over the selected text.
As Illustrated:
I also haven't decided on positioning (I like the way that it's illustrated) but to clarify, that's not the point of the question.
The question is: How do I filter for a hover event that happens over selected text?
The Problems:
To my mind, the ideal solution is somehow to calculate the region of the selected text and test whether mouseover events happen in that region.
On mouseup
, use Range.getClientRects to grab the bounding rectangles of each line of the selection.
You can then test if the mouse is over the selection like this:
var cr= [];
$(document).on({
'mouseup': function() {
cr= window.getSelection().getRangeAt(0).getClientRects();
},
'mousemove': function(ev) {
//hide the pop up
for(var i = 0 ; i < cr.length ; i++) {
if(ev.pageX >= cr[i].left && ev.pageX <= cr[i].right &&
ev.pageY >= cr[i].top && ev.pageY <= cr[i].bottom
) {
//show the pop up
break;
}
}
}
});
这篇关于检测选定文本上的悬停的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!