在 JavaScript 范围对象中检测换行符的问题
我有一些 javascript 可以根据用户选择的内容来操作 html.对于真正的浏览器,我使用的方法利用了Range"对象,如下所示:
I have some javascript that manipulates html based on what the user has selected. For real browsers the methods I'm using leverage the "Range" object, obtained as such:
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var content = range.toString();
内容变量包含所有选定的文本,效果很好.但是我发现我无法检测到结果字符串中的换行符.例如:
The content variable contains all the selected text, which works fine. However I'm finding that I cannot detect the newlines in the resulting string. For example:
所选文字是:
abc
定义
ghi
range.toString() 计算结果为abcdefghi".
range.toString() evaluates to "abcdefghi".
对特殊字符的任何搜索都不会返回 f 甚至 s 的实例.但是,如果我将变量写入可编辑控件,则会再次出现换行符.
Any search on special characters returns no instance of f or even s. If, however, I write the variable out to an editable control, the line feeds are present again.
有人知道我错过了什么吗?
Does anyone know what I'm missing?
这些选择和操作在可编辑的 div 上可能是相关的.同样的行为在 Chrome、FireFox 和 Opera 中也很明显.令人惊讶的是,IE 需要完全不同的代码,但除了 IE 之外没有任何问题.
It may be relevant that these selections and manipulations are on editable divs. The same behaviour is apparent in Chrome, FireFox and Opera. Surprisingly IE needs totally different code anyway, but there aren't any issues there, other than it just being IE.
非常感谢.
推荐答案
编辑我的帖子:
实验了一下,我发现 sel.toString()
在 contenteditable div 中返回新行,而 range.toString()
在正常不可编辑的情况下正确返回换行div,但不是可编辑的,正如您所报告的那样.
Experimenting a bit, I find that sel.toString()
returns new lines in contenteditable divs, while range.toString()
returns newlines correctly in normal non-editable divs, but not in editable ones, as you reported.
但无法找到该行为的任何解释.
Could not find any explanation for the behaviour though.
这是一个有用的链接 http://www.quirksmode.org/dom/range_intro.html
相关文章