我正在构建一个WYSIWYG富文本编辑器。
当用户选择他/她的部分文本时,我想在工具提示中显示一个菜单。呈现菜单工作正常,但我想只显示用户将鼠标悬停在所选文本上。
如图所示:
我还没有决定定位(我喜欢它的说明方式),但澄清一下,这不是问题的重点。
问题是:如何过滤所选文字上发生的悬停事件?
问题:
我不能只是监听文本选择事件或测试悬停事件,看看它们是否覆盖了在其中选择了文本的元素。左图将产生误报。
我知道如何获取所选文字,但我不知道如何获取 所选区域 。
在我看来,理想的解决方案以某种方式计算所选文本的区域,并测试鼠标悬停事件是否发生在该区域。
答案 0 :(得分:3)
在mouseup
上,使用Range.getClientRects抓取所选内容的每一行的边界矩形。
然后,您可以测试鼠标是否超出选择范围,如下所示:
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;
}
}
}
});
答案 1 :(得分:2)
尝试这种方式:
<强> JS 强>
$(document).ready(function () {
$(document).on("mouseup", ".conttext", function () {
var highlight = window.getSelection();
console.log(highlight);
var spn = '<span class="highlight">' + highlight + '</span>';
var text = $('.conttext').text();
$('.conttext').html(text.replace(highlight, spn));
});
$(document).on("mouseover", ".highlight", function () {
alert("You hovered on selected tex"); // Your tooltip code goes here
})
});
<强> CSS:强>
.highlight {
color:#888;
position:relative;/*This will not matter if you inject tooltip using JS*/
display:inline-block;/*This will not matter if you inject tooltip using JS*/
}
HTML:
<div class="conttext">Sample text</div>