在Javascript中按范围设置选择

时间:2013-07-16 11:14:23

标签: javascript range textselection

我想通过使用Javascript发送location / anchorOffset和length / offset来选择文本这是我的代码

  var node = document.getElementById("content");
   var range = document.createRange();
   range.setStart(node, 0);
   range.setEnd(node, 4); // here 0 and 4 is my location and length for the selection
       // if my string is "This is test string" in my case its must select "This" 
   var selection = window.getSelection();
   selection.removeAllRanges();
    selection.addRange(range);

但问题在于range.setStart和range.setEnd它没有像我期望的那样工作

2 个答案:

答案 0 :(得分:15)

DOM范围的setStart()setEnd()方法已明确指定,因此您可以通过阅读the specMDN找到答案。

总而言之,如果要根据字符偏移指定范围边界,则需要处理文本节点而不是元素。如果您的元素包含单个文本节点,则将代码的第一行更改为以下内容将起作用:

var node = document.getElementById("content").firstChild;

答案 1 :(得分:13)

Here's a good solution if you're trying to select a jquery result set

var $newSelection = $('.someElements');
var selection = window.getSelection();
var range = document.createRange();
range.setStartBefore($newSelection.first()[0]);
range.setEndAfter($newSelection.last()[0]);
selection.removeAllRanges();
selection.addRange(range);