检测JavaScript范围对象中的换行符的问题 [英] Problem detecting Newlines in JavaScript Range Object

查看:100
本文介绍了检测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

def

ghi

range.toString()评估为abcdefghi。

range.toString() evaluates to "abcdefghi".

对特殊字符的任何搜索都不会返回\\\
\f \r甚至\s的实例。但是,如果我将变量写入可编辑控件,则会再次显示换行符。

Any search on special characters returns no instance of \n \f \r 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

这篇关于检测JavaScript范围对象中的换行符的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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