计算文本选择的xy位置 [英] Calculating xy-position of text selection

查看:66
本文介绍了计算文本选择的xy位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用DOM元素创建自己的文本选择.是的,我的意思是当您在此元素中选择文本时,您会在文本后面看到蓝色背景.想法是停止默认行为(蓝色),并通过查找所选内容的xy位置,然后放置绝对定位的元素,使用我自己的元素来完成此工作.我希望能够使用常规的 div .

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.

我认为我需要3个要素.一个用于第一行(可能是不完整的),一个用于中间的块,一个用于最后的块(与顶部相同).这是一张可以帮助您理解的图像:

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:

我一直想捕获 mouseup/down ,然后捕获 mousemove ,然后检查 window.getSelection(),但到目前为止,我我无法到达任何地方.

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.

使用CSS :: selection 无效,因为该元素没有焦点.

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

我感谢我能获得的所有帮助!预先感谢.

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

偶然发现 https://code.google.com/p/rangy/有帮助吗?任何有使用此插件经验的人?

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.

推荐答案

您可以使用getClientRnge:

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.

这篇关于计算文本选择的xy位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆