Javascript获取与父元素相比的范围 [英] Javascript get range compared to a parent element

查看:56
本文介绍了Javascript获取与父元素相比的范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数返回一个包含两个元素的数组(在 IE 中不起作用)

  • 用户在 div 中选择的 html 代码(id=text)
  • 选择范围

如果用户在文本 div 中选择一个简单的字符串,则范围返回正确的值,但是当用户在 div 的元素子级(例如 div#text->p)中选择一个字符串时,范围的值与子元素,但我希望它们与父元素相关 (div#text)

这里有一个 JsFiddle http://jsfiddle.net/paglia_s/XKjr5/:如果你在teatarea中选择一串普通文本或普通文本+粗体文本,您将获得正确的选择,而如果您选择粗体字(am"),您将得到错误的选择,因为范围与子元素相关.

有一种方法可以使范围始终与 div#text 相关吗?

解决方案

你可以使用我的 Rangy 库及其新的 TextRange 模块,提供范围和选择的方法在容器元素的可见文本中与字符偏移量相互转换.例如:

var container = document.getElementById("text");var sel = rangy.getSelection();如果(sel.rangeCount > 0){var range = sel.getRangeAt(0);var rangeOffsets = range.toCharacterRange(container);}

rangeOffsets 具有相对于 container 中的可见文本的属性 startend.可见文本不一定与 jQuery 的 text() 方法返回的内容相同,因此您需要使用 Rangy 的 innerText() 实现.示例:

http://jsfiddle.net/timdown/KGMnq/5/

或者,如果你不想使用 Rangy,你可以调整我的函数 之前在 Stack Overflow 上发表过.但是,这些依赖于 DOM 范围和选择 API,因此不适用于 IE <9.

I have a function that return an array (won't work in IE) with two elements

  • the html code of what the user select inside a div (id=text)
  • the range of the selection

In case the user select a simple string inside the text div the range return the correct values but when the user select a string inside an element child of div (div#text->p for example) range's values are related to the child element but i want them to be related to the parent (div#text)

Here there's a JsFiddle http://jsfiddle.net/paglia_s/XKjr5/: if you select a string of normal text or normal text + bolded text in the teatarea you'll get the right selection while if you select the bolded word ("am") you'll get the wrong one because the range is related to the child element.

There's a way to do so that the range is always related to div#text?

解决方案

You could use my Rangy library and its new TextRange module, which provides methods of Range and selection to convert to and from character offsets within the visible text of a container element. For example:

var container = document.getElementById("text");
var sel = rangy.getSelection();
if (sel.rangeCount > 0) {
    var range = sel.getRangeAt(0);
    var rangeOffsets = range.toCharacterRange(container);
}

rangeOffsets has properties start and end relative to the visible text inside container. The visible text isn't necessarily the same as what jQuery's text() method returns, so you'll need to use Rangy's innerText() implementation. Example:

http://jsfiddle.net/timdown/KGMnq/5/

Alternatively, if you don't want to use Rangy, you could adapt functions I've posted on Stack Overflow before. However, these rely on DOM Range and Selection APIs so won't work on IE < 9.

这篇关于Javascript获取与父元素相比的范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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