boundingclientrect of range
HTML
<p id='test'>click the <a href='javascript:;'>sample words</a> here</p>
<pre id='result'></pre>
<p class='tips'>
click the "sample" or "words" above,and the corresponding range will be lighlighted.The word "sample" not work properly.
</p>
<div id='client-rect'></div>
CSS
#result {
border:1px dashed green;
}
.tips {
color:brown;
}
#client-rect {
position:absolute;
background-color:rgba(255,0,0,0.5);
pointer-events:none;
}
JavaScript
document.querySelector('#test').addEventListener('mousedown',function(e) {
if (!document.caretRangeFromPoint) {
return;
}
var range = document.caretRangeFromPoint(e.clientX, e.clientY);
if (!range.expand) {
return;
}
range.expand("word");
console.log(range.toString());
var rect = range.getBoundingClientRect();
document.querySelector('#result').innerText = JSON.stringify(rect,null,4);
//highlight the range
var clientRectDiv = document.querySelector('#client-rect');
clientRectDiv.style.width = rect.width+'px';
clientRectDiv.style.height = rect.height+'px';
clientRectDiv.style.left = rect.left+'px';
clientRectDiv.style.top = rect.top+'px';
},false);