计算所选文本 javascript/JQuery 的位置?

Calculate Position of selected text javascript/JQuery?(计算所选文本 javascript/JQuery 的位置?)

本文介绍了计算所选文本 javascript/JQuery 的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何通过计算正文标记后的偏移量来检索选定文本的位置?

How to retrieve the position of selected text by calculating it's offset immediate after body tag?

例如考虑以下html,

For Example consider the following html,

<body> <div>hi</div> <div>dude!</div> </body>

在从i"(嗨)到du"(在花花公子)中选择时,我需要将 2 作为起始位置 &4 作为结束位置.

on selecting from "i" (in hi) to "du" (in dude), I need to get 2 as start position & 4 as end position.

注意:忽略标签元素.

最好使用Javascript!

Javascript is preferable!

推荐答案

这里有一些简单、幼稚的代码来执行此操作,它们可能很适合您的用例.它不考虑任何可能变得不可见的文本(例如,通过 CSS 或通过在 a or 元素内),并且可能存在带有换行符的浏览器差异(IE 与其他所有内容),并且不考虑折叠的空白(例如 2 个或更多连续的空格字符折叠到页面上的一个可见空间).但是,它在所有主流浏览器中都适用于您的示例.

Here's some simple, naive code to do this that may well do the job for your use case. It does not take into account any text that may be made invisible (either by CSS or by being inside a or element, for example) and may have browser discrepancies (IE versus everything else) with line breaks, and takes no account of collapsed whitespace (such as 2 or more consecutive space characters collapsing to one visible space on the page). However, it does work for your example in all major browsers.

现场演示:http://jsfiddle.net/UuDpL/2/

代码:

function getSelectionCharOffsetsWithin(element) {
    var start = 0, end = 0;
    var sel, range, priorRange;
    if (typeof window.getSelection != "undefined") {
        range = window.getSelection().getRangeAt(0);
        priorRange = range.cloneRange();
        priorRange.selectNodeContents(element);
        priorRange.setEnd(range.startContainer, range.startOffset);
        start = priorRange.toString().length;
        end = start + range.toString().length;
    } else if (typeof document.selection != "undefined" &&
            (sel = document.selection).type != "Control") {
        range = sel.createRange();
        priorRange = document.body.createTextRange();
        priorRange.moveToElementText(element);
        priorRange.setEndPoint("EndToStart", range);
        start = priorRange.text.length;
        end = start + range.text.length;
    }
    return {
        start: start,
        end: end
    };
}

alert( getSelectionCharOffsetsWithin(document.body).start );

这篇关于计算所选文本 javascript/JQuery 的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:计算所选文本 javascript/JQuery 的位置?

基础教程推荐