IE:有没有一种快速方法可以在设计模式下获取 iframe 中的插入符位置?

发布于 2024-10-06 15:25:51 字数 476 浏览 0 评论 0原文

我试图在 IE8 的设计模式下获取 iframe 内某些文本的插入符位置。 我的代码可以工作,但对于长文本,它的性能很差而且丑陋,因为它选择所有文本,然后开始一次移动一个字符范围的末尾。

我想知道是否有一种更快、更优雅的方法来获取 IE 中当前插入符的位置?这是我当前的代码:

var r = doc.selection.createRange();
r.collapse(false);
doc.execCommand("SelectAll") //this is ugly..
var r2 = doc.selection.createRange();
r2.select();
//..and this is slow
while (r.compareEndPoints("EndToEnd", r2) < 0) {
   r2.moveEnd("character", -1)
   r2.select();
}
pos = r2.text.length;

I am trying to get the caret position for some text inside an iframe in design mode, in IE8.
The code I have works, but for long texts it performs badly and ugly, because it selects all the text and then starts moving the end of the range one character at a time.

I wonder if there is a faster and more elegant way to get the current caret position in IE? here is my current code:

var r = doc.selection.createRange();
r.collapse(false);
doc.execCommand("SelectAll") //this is ugly..
var r2 = doc.selection.createRange();
r2.select();
//..and this is slow
while (r.compareEndPoints("EndToEnd", r2) < 0) {
   r2.moveEnd("character", -1)
   r2.select();
}
pos = r2.text.length;

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

﹏半生如梦愿梦如真 2024-10-13 15:25:51

是的,您可以使用我的 Rangy 库,它为您提供了在所有浏览器中执行此操作的单一方法使用 DOM Level 2 Range 界面。下面假设您将 iframe 的 window 对象存储在名为 iframeWin 的变量中:

var sel = rangy.getSelection(iframeWin);
if (sel.rangeCount > 0) {
    var selectedRange = sel.getRangeAt(0);
    alert(selectedRange.toString());
}

用于将 IE 的 TextRange 对象转换为 DOM Range 对象的过程Rangy 比您已有的更复杂、更快(至少对于长文档)。如果您感兴趣,相关代码位于此文件的顶部附近:http://code.google.com/p/rangy/source/browse/trunk/src/js/core/wrappedrange.js

Yes, you can use my Rangy library, which gives you a single way of doing this in all browsers using the DOM Level 2 Range interface. The following assumes you have the iframe's window object stored in a variable called iframeWin:

var sel = rangy.getSelection(iframeWin);
if (sel.rangeCount > 0) {
    var selectedRange = sel.getRangeAt(0);
    alert(selectedRange.toString());
}

The process used to convert IE's TextRange objects into DOM Range objects in Rangy is more sophisticated and much faster (for long documents, at least) than what you already have. If you're interested, the relevant code is near the top of this file: http://code.google.com/p/rangy/source/browse/trunk/src/js/core/wrappedrange.js

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文