我正在尝试将 a<div>
放置在用户文本选择上方,该文本选择将充当类似于 Mediums 的工具栏。
虽然我已经成功<div>
地将 定位在选择旁边,但我似乎无法让它相对于选择正确居中:
$(function() {
// Setup the Event Listener
$('.article').on('mouseup', function() {
// Selection Related Variables
let selection = window.getSelection(),
getRange = selection.getRangeAt(0),
selectionRect = getRange.getBoundingClientRect();
// Set the Toolbar Position
$('.toolbar').css({
top: selectionRect.top - 42 + 'px',
left: selectionRect.left + 'px'
});
});
});
我可以通过从视口中减去选择的左偏移量来确定选择的中心点,如下所示:
selectionRect.left - selectionRect.width
但是,我不确定如何使用它来将工具栏的位置设置为相对于选择矩形居中?
我尝试从选择的宽度除以 2 中减去工具栏的左偏移量,但这也不能完全与中心对齐。
JSFiddle