Assuming something selected
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
rect
is now a Object which holds the positions relative the the current scroll coordinates of the Window. More info on this here. If you want to be even more precise, you can use getClientRects
which returns a list of such Objects, which you would then have to put together to form the area of the selection.
Now, to draw a box around it (I'll take the easy route using fixed
for demonstration purposes)
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
You will probably want to take into consideration the scroll position so you can use absolute positioning. If there are no other scrollable elements, this means you just need to factor in the values of window.scrollX
and window.scrollY
, which are the position of the window's x and y coordinates in pixels at the time they're accessed.
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;
<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>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…