通过Javascript计算HTML中的开始和结束选择索引 [英] Calculating start and end selection indices in HTML through Javascript

查看:84
本文介绍了通过Javascript计算HTML中的开始和结束选择索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在contentEditable'div'中的IE以外的浏览器中获得开始和结束选择索引。例如,IE有以下方法。

How can I get the start and end selection indices in browsers other than IE in contentEditable 'div'. For Ex., IE has the following method.

var oSelection;
var oTxtRange;
var units = -100000;
var iStartIndex = -1, iEndIndex = -1;

if(document.selection)      // IE..
{
  oSelection = document.selection;
  oTxtRange = oSelection.createRange();

  if(oTxtRange)
  {
    iStartIndex = oTxtRange.moveStart('character',units);
    iEndIndex = oTxtRange.moveEnd('character',units);
    iStartIndex *= -1;
    iEndIndex *= -1;
  }
}

我明白上述方法不是W3C标准。我已经浏览了选择和范围对象的W3C文档,但仍然无法帮助查找Chrome和FireFox的解决方案。我们也欢迎JQuery的解决方案。

I understand that above method is not a W3C standard. I have gone through W3C documentation for Selection and Range object, but still couldn't help finding solution for Chrome and FireFox. Solution in JQuery is also welcome.

在此先感谢: - )

Thanks in Advance :-)

推荐答案

你可以在非IE浏览器中执行下列操作。它返回页面的可见正文文本中的选择边界的偏移量,就像IE版本一样,但我不确定这些数字的用途是什么。

You can do something like the following in non-IE browsers. It returns offsets of the selection boundaries within the visible body text of the page like the IE version does, but I'm not sure what use these numbers will be.

function getBodyTextOffset(node, offset) {
    var sel = window.getSelection();
    var range = document.createRange();
    range.selectNodeContents(document.body);
    range.setEnd(node, offset);
    sel.removeAllRanges();
    sel.addRange(range);
    return sel.toString().length;
}

function getSelectionOffsets() {
    var sel, range;
    var start = 0, end = 0;
    if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
            range = sel.getRangeAt(sel.rangeCount - 1);
            start = getBodyTextOffset(range.startContainer, range.startOffset);
            end = getBodyTextOffset(range.endContainer, range.endOffset);
            sel.removeAllRanges();
            sel.addRange(range);
            alert(start + ", " + end);
        }
    } else if (document.selection) {
        // IE stuff here
    }
    return {
        start: start,
        end: end
    };
}

这篇关于通过Javascript计算HTML中的开始和结束选择索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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