通过代码

时间:2015-07-19 01:32:01

标签: javascript

是否可以使用代码在div中选择特定文本。我有一个文本div,我需要遍历每个单词,单独选择它,然后选择下一个单词。

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

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

------------------------ UPDATE ---------------------- --------------------

好的,这就是我今天再看一遍它的地方。我可以选择范围内的所有文本,但不能特别选择该范围内的一系列文字。我最接近的代码(下面显示的代码......)是手动选择范围,然后删除选择,然后重新应用它。

<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属性。我的问题是如何通过代码(而不是通过鼠标选择)将其与初始选择一起设置?

2 个答案:

答案 0 :(得分:0)

请阅读这篇文章,很难总结,所以请更好地阅读:

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

这里的答案也很有用:

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

答案 1 :(得分:0)

原来这很简单......

<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>