Javascript 检测选定文本上的悬停
我正在构建一个WYSIWYG富文本编辑器 当用户选择他/她的文本的一部分时,我想在工具提示中显示一个菜单。显示菜单很好,但我只想在用户将鼠标悬停在所选文本上时显示它 如图所示:Javascript 检测选定文本上的悬停,javascript,jquery,html,Javascript,Jquery,Html,我正在构建一个WYSIWYG富文本编辑器 当用户选择他/她的文本的一部分时,我想在工具提示中显示一个菜单。显示菜单很好,但我只想在用户将鼠标悬停在所选文本上时显示它 如图所示: .highlight { color:#888; position:relative;/*This will not matter if you inject tooltip using JS*/ display:inline-block;/*This will not matter if you
.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*/
}
我还没有决定定位(我喜欢它的图示方式),但要澄清的是,这不是问题的重点
问题是:如何筛选在选定文本上发生的悬停事件
问题:
.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*/
}
$(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
})
});
HTML:
示例文本
演示:在
mouseup
上,用于抓取选择的每一行的边界矩形
然后,您可以测试鼠标是否位于选择上,如下所示:
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;
}
}
}
});
var cr=[];
$(文件)({
“mouseup”:函数(){
cr=window.getSelection().getRangeAt(0.getClientRects();
},
“mousemove”:函数(ev){
//隐藏弹出窗口
对于(变量i=0;i 如果(ev.pageX>=cr[i]。左(&ev.pageX=cr[i].top&&ev.pageY是否有帮助?这只会获取选定的文本:我实际上需要某种方法来获取浏览器在屏幕上绘制的区域。可能您可以将选定的文本包装在一个标记中,并将悬停绑定到特定的标记?@LShetty这主意不错,我希望有一个更优雅的解决方案。这可能意味着人为地重新设置选择文本时可能会遇到问题,当用键盘修改选择时可能会遇到问题。不确定,必须进行试验。@l如果选择的部分文本样式过重,也会出现问题-html变得无效hello world lorem
那么像hello world lorem
这样的情况如何?(考虑到这一点是所见即所得编辑)在这种情况下,您可以参考此解决方案:。您在帖子中只提到了文本,而我在解决方案中考虑了文本。但是,此解决方案可以帮助您修改或更新代码。此代码在替换文本后不会保留插入符号位置。