【问题标题】:Selecting parts of div text via the code通过代码选择部分 div 文本
【发布时间】:2015-07-22 23:25:25
【问题描述】:

是否可以使用代码选择 div 内的特定文本。我有一个文本 div,我需要遍历每个单词,分别选择它,然后删除并进入下一个单词。

我不是在谈论通过更改需要突出显示的单词的背景 css 来模拟选择,而是实际选择它,因此结果与用户使用鼠标选择它时的结果相同。

我知道它可以在文本区域输入中,但它可以在 Div 上吗?

----------更新---------- --------------------

好的,这就是我今天再看一遍后的位置。我可以选择一个跨度中的所有文本,但不能选择该跨度内的特定单词范围。我最接近的(代码如下所示...)是手动选择范围,然后删除选择,然后重新应用它。

<div contentEditable = 'true' id="theDiv">
A selection of words but only from here to here to be selected
</div>
<script type="text/javascript"> 
setInterval( function() {
    var currSelection = window.getSelection();
    var storedSelections = [];

    if ( currSelection ) {
        for (var i = 0; i < currSelection.rangeCount; i++) {
            storedSelections.push (currSelection.getRangeAt (i));
        }
        currSelection.removeAllRanges ();
    }

    if ( storedSelections.length != 0 ) {
        currSelection.addRange( storedSelections[0] )
    } 
}, 1000 );
</script>

存储的选择范围对象具有 startOffset 和 endOffset 属性。我的问题是如何通过代码(而不是通过鼠标选择)将其与初始选择一起设置?

【问题讨论】:

  • 你想做什么?提供更多关于您想要的结果的信息。
  • 这绝对是可能的,因为 HTML 编辑器将我们的 DIV 与 'contenteditable' 结合使用来实现与您正在尝试做的事情相关的事情(这里假设)。
  • 你关心哪些浏览器? Selections API 允许这样做,但 IE 不支持(Edge 会有)
  • 是的,我研究了 contenteditable,希望它能让 div 像文本区域一样发挥作用,但不幸的是它没有。
  • 只需要与 chrome 兼容

标签: javascript


【解决方案1】:

请阅读这篇文章,很难概括,所以最好阅读它:

http://www.quirksmode.org/dom/range_intro.html

这里的答案也很有用:

Can you set and/or change the user’s text selection in JavaScript?

【讨论】:

  • 尽管我很喜欢 PPK,但 Quirksmode 的那篇文章似乎已经很老了;我不确定它今天还有多少用途。
  • 好吧,我想他至少会知道这是如何工作的,以及他应该进一步了解什么
  • 不幸的是,quirksmode 没有提供答案。它建议设置文本范围的方法不起作用。
【解决方案2】:

事实证明它相当简单......

<div id = "theDiv">adsf asdf asdf asdf</div>

<script type="text/javascript">
    var theDiv = document.getElementById('theDiv')
    theDivFirstChild = theDiv.firstChild;
    var range = document.createRange();
    range.setStart( theDivFirstChild, 2 );
    range.setEnd( theDivFirstChild, 8);
    window.getSelection().addRange(range);
</script> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-17
    • 2012-03-01
    • 2014-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多