Nav*_*eed 9 javascript jquery html5 selection textselection
我的最终目标是在文本选择上创建工具提示.然后,用户将能够与类似的工具提示进行交互
.请注意,我能够通过将选定的文本包装在标签中然后在其上创建工具提示来实现此目的,但由于某些其他要求和功能问题,这不再是我的选择.如果您在元素检查器中的上图中注意到,所选文本未包含在任何类型的标记中,则仅在选择上创建工具提示.我已经看过这个并且它对我不起作用,因为鼠标位置可能与选择结束不同.我需要实际的选择位置.
一般问题:实现这一目标的最佳方法是什么?更具体的问题:
Pau*_* S. 14
假设选择了一些东西
var selection = window.getSelection(), // get the selection then
range = selection.getRangeAt(0), // the range at first selection group
rect = range.getBoundingClientRect(); // and convert this to useful data
Run Code Online (Sandbox Code Playgroud)
rect现在是一个Object,它保存相对于Window的当前滚动坐标的位置.在此更多信息在这里.如果你想要更精确,你可以使用getClientRects它返回这些对象的列表,然后你必须将它们放在一起以形成选择区域.
现在,在它周围画一个盒子(我将采用简单的路线fixed用于演示目的)
var div = document.createElement('div'); // make box
div.style.border = '2px solid black'; // with outline
div.style.position = 'fixed'; // fixed positioning = easy mode
div.style.top = rect.top + 'px'; // set coordinates
div.style.left = rect.left + 'px';
div.style.height = rect.height + 'px'; // and size
div.style.width = rect.width + 'px';
document.body.appendChild(div); // finally append
Run Code Online (Sandbox Code Playgroud)
您可能需要考虑滚动位置,以便使用绝对定位.如果没有其他可滚动的元素,这意味着你只需要在该值因素window.scrollX和window.scrollY,这是窗户的位置X和Ÿ坐标在他们访问的时间像素.
var div = null;
function drawBorderAroundSelection() {
var selection = window.getSelection(), // get the selection then
range = selection.getRangeAt(0), // the range at first selection group
rect = range.getBoundingClientRect(); // and convert this to useful data
if (rect.width > 0) {
if (div) {
div.parentNode.removeChild(div);
}
div = document.createElement('div'); // make box
div.class = 'rect';
div.style.border = '2px solid black'; // with outline
div.style.position = 'fixed'; // fixed positioning = easy mode
div.style.top = rect.top + 'px'; // set coordinates
div.style.left = rect.left + 'px';
div.style.height = rect.height + 'px'; // and size
div.style.width = rect.width + 'px';
document.body.appendChild(div); // finally append
}
}
window.onmouseup = drawBorderAroundSelection;Run Code Online (Sandbox Code Playgroud)
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut dolor porta neque vulputate auctor et a ligula. Quisque bibendum risus magna, eget feugiat erat faucibus sed. Phasellus sed massa elementum, laoreet ipsum non, dignissim orci. Aenean lobortis
nunc et purus molestie, vel consectetur ligula dapibus. In ut lorem mattis, commodo nisi aliquam, porta ante. Curabitur sit amet libero sed justo finibus porttitor. Donec ac est ultrices, pretium diam sed, blandit nunc. Morbi consequat finibus augue
vel ultricies. Vestibulum efficitur ante vitae cursus accumsan. Vestibulum rutrum ex ex, a egestas nisi malesuada eu. Pellentesque fermentum, ante id convallis luctus, tellus lectus viverra diam, sit amet convallis ligula lorem sit amet neque.
</p>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6255 次 |
| 最近记录: |