Calculating xy-position of text selection

有些话、适合烂在心里 提交于 2019-12-11 01:33:45

问题


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:

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 https://code.google.com/p/rangy/ which might be of help? Anyone with experience with this plugin?

Edit2: Cross-browser support is required.


回答1:


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)
}

http://jsfiddle.net/XjHtG/

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



来源:https://stackoverflow.com/questions/17566323/calculating-xy-position-of-text-selection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!