Javascript 如何在选择的中间突出显示文本时显示弹出窗口?
我使用JavaScript在文本突出显示上显示一个弹出窗口。但我无法将其定位在突出显示的中心 与medium.com文本突出显示弹出窗口相同。我希望Javascript 如何在选择的中间突出显示文本时显示弹出窗口?,javascript,html,css,Javascript,Html,Css,我使用JavaScript在文本突出显示上显示一个弹出窗口。但我无法将其定位在突出显示的中心 与medium.com文本突出显示弹出窗口相同。我希望.toolbar位于突出显示文本的中心,如下图所示 const getRoot=document.querySelector('.root'), getTool=document.querySelector('.toolbar'); document.addEventListener('mouseup',e=>{ window.getSelecti
.toolbar
位于突出显示文本的中心,如下图所示
const
getRoot=document.querySelector('.root'),
getTool=document.querySelector('.toolbar');
document.addEventListener('mouseup',e=>{
window.getSelection().toString().length?
(
getTool.style.left=e.clientX+'px',
getTool.style.top=e.clientY+'px',
getTool.classList.add('active')
):null;
});
document.addEventListener('mousedown',()=>{
window.getSelection().toString().length是否小于1?
getTool.classList.remove('active'):null;
});代码>
*,
*::之前,
*::之后{
框大小:边框框;
}
身体{
保证金:0;
}
.根{
最大宽度:500px;
保证金:1rem自动;
字号:21px;
线高:1.8;
字体系列:时代新罗马;
}
.工具栏{
显示:无;
位置:绝对位置;
高度:45px;
宽度:220px;
背景色:#212121;
边界半径:.25rem;
过渡:.2s;
}
.toolbar.active{
显示:块;
}
我的同僚们都是精英。这是一个很好的解决方案。洛勒姆
同一天,我坐在同一棵树上。建筑师,尚特
像这样,您应该使用选择范围和范围边界ClientRect
document.addEventListener('mouseup', e => {
s = window.getSelection()
oRange = s.getRangeAt(0); //get the text range
oRect = oRange.getBoundingClientRect();
s.toString().length ?
(
getTool.style.left = ((oRect.left + oRect.width / 2) -110) + 'px', // 110 is toolbox.width/2
getTool.style.top = (oRect.top - 45 - 10) + 'px', //45 is toolbow.height
getTool.classList.add('active')
) : null;
});
请尽量让代码片段正常工作,以便其他人能够轻松理解您的问题代码片段确实正常工作是的,我意识到我自己已经选择了文本。我认为您非常接近,下面的答案可能会帮助您非常感谢。