我正在尝试将<div>
放置在用户文本选择上方,该文本选择将充当类似于“媒介”的工具栏。
虽然我已经成功地将<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'
});
});
});
我可以这样确定选区的中心点:减去选区的宽度,使选区从视口(viewport)向左偏移:
selectionRect.left - selectionRect.width
但是,我不确定如何使用它来设置工具栏的位置相对于选择矩形居中?
我尝试从选择的宽度除以2减去工具栏的左偏移量,但这也不完美地与中心对齐。
JSFiddle
https://jsfiddle.net/e64jLd0o/
最佳答案
一种解决方案是将以下内容添加到您的CSS中:
.toolbar {
transform: translateX(-50%);
}
并更新脚本以抵消工具栏元素的左侧位置,如下所示:
$('.toolbar').css({
top: selectionRect.top - 42 + 'px',
left: ( selectionRect.left + (selectionRect.width * 0.5)) + 'px'
});
这是一个有效的代码段:
$(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'
});
});
});
.article {
position: relative;
height: 300px;
padding: 20px;
}
.toolbar {
position: absolute;
display: flex;
align-items: center;
justify-content: center;
width: 169px;
padding-top: 10px;
padding-bottom: 10px;
background: black;
text-align: center;
color: white;
border-radius: 8px;
transform: translateX(-50%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<!-- Editor -->
<div class="article">
<p>Lorem ipsum dolor, sit amet consectetur adipisicing elit. Tenetur dignissimos facilis id repellat sint deserunt voluptates animi eaque tempore debitis, perferendis repudiandae voluptatem. Eligendi fuga deleniti saepe quod eum voluptas.</p>
</div>
<!-- Toolbar -->
<div class="toolbar">Toolbar</div>