Calculating xy-position of text selection

I am trying to create my own text selection with DOM-elements. Yes, I mean the blue background you see behind the text when you select it in this element. The idea is to halt the default behavior (the blue color) and use my own elements to do the job by finding the xy-position of the selection and then placing absolute positioned elements. I want to be able to do this with a regular div.

I'm thinking I need 3 elements. One for the top row (which may be incomplete), one for the middle chunk, one for the last (same as top). Here's an image that helps you understand: <img src="" alt="Image showing the needed selection elements">

I've been thinking of catching mouseup/down and then mousemove and then check window.getSelection() but so far I'm having trouble getting anywhere.

Using the CSS ::selection will not work because the element will not have focus.

I appreciate all help I can get! Thanks in advance.

Edit: Stumbled upon which might be of help? Anyone with experience with this plugin?

Edit2: Cross-browser support is required.


You can use getClientRnge:

var element = document.getElementById('element') element.onmouseup = function(){ var selection = document.getSelection(), range = selection.getRangeAt(0), clientRects = range.getClientRects() console.log(clientRects) }

This will return the left, right, top, bottom, width and height of all selections made.

人吐槽 人点赞



用户名: 密码:
验证码: 匿名发表


查看评论:Calculating xy-position of text selection