JavaScript:将DIV定位在文本选择上方吗?

Miu*_*shi 3 html javascript getboundingclientrect

我试图将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'
        });
      });
    });
Run Code Online (Sandbox Code Playgroud)

我可以这样确定选区的中心点:减去选区的宽度,使选区从视口向左偏移:

 selectionRect.left - selectionRect.width
Run Code Online (Sandbox Code Playgroud)

但是,我不确定如何使用它来设置工具栏相对于选择矩形居中的位置吗?

我尝试从选择的宽度除以2减去工具栏的左偏移量,但这也不完全与中心对齐。

JSFiddle

https://jsfiddle.net/e64jLd0o/

Dac*_*nny 5

一种解决方案是将以下内容添加到您的CSS中:

.toolbar {
  transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)

并更新脚本以抵消工具栏元素的左侧位置,如下所示:

$('.toolbar').css({
  top: selectionRect.top - 42 + 'px',
  left: ( selectionRect.left + (selectionRect.width * 0.5)) + 'px'
});
Run Code Online (Sandbox Code Playgroud)

这是一个工作片段:

.toolbar {
  transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)
$('.toolbar').css({
  top: selectionRect.top - 42 + 'px',
  left: ( selectionRect.left + (selectionRect.width * 0.5)) + 'px'
});
Run Code Online (Sandbox Code Playgroud)
$(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 + (selectionRect.width * 0.5)) + 'px'
    });
  });
});
Run Code Online (Sandbox Code Playgroud)


Gly*_*ine 5

为了快速编辑,我应用了正确定位 div 所需的更改:

https://jsfiddle.net/yaLvzswu/

我在left计算中应用了一些额外的定位数学:

$(function() {
  // Setup the Event Listener
  $('.article').on('mouseup', function() {
    // Selection Related Variables
    let selection = window.getSelection(),
    getRange      = selection.getRangeAt(0),
    selectionRect = getRange.getBoundingClientRect();
        console.log(selectionRect)
    // Set the Toolbar Position
    $('.toolbar').css({
      top: selectionRect.top - 42 + 'px',
      left: (selectionRect.left - ($('.toolbar').width()/2) + (selectionRect.width/2))+ 'px'
    });
  });
});
Run Code Online (Sandbox Code Playgroud)

您的版本将工具栏的左侧应用于所选文本的左侧。由于我们希望将工具栏的中心放在所选内容的中心,因此左侧被打乱两次:

  • 从左开始
  • 向左移动工具栏宽度的一半

现在工具栏中心位于选择的左侧。

  • 添加选择宽度的一半

工具栏向右移动了一点 - 所选文本的中心。