javascript 在Javascript中按范围设置选择

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17675056/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:09:49  来源:igfitidea点击:

Set selection by range in Javascript

javascriptrangetextselection

提问by Shinning River

I want to select text by sending location/anchorOffset and length/offset using Javascript Here is my code

我想通过使用 Javascript 发送位置/anchorOffset 和长度/偏移来选择文本这是我的代码

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

But the issue is with range.setStart and range.setEnd its not working as I expect

但问题在于 range.setStart 和 range.setEnd 它不像我预期的那样工作

采纳答案by Tim Down

The setStart()and setEnd()methods of DOM Range are well specified, so you could find the answer by reading the specor MDN.

DOM Range的setStart()setEnd()方法被很好地指定,所以你可以通过阅读规范MDN找到答案。

To summarise, if you want to specify a range boundary in terms of character offsets, you need to deal with a text node rather than an element. If your element contains a single text node, changing the first line of your code to the following will work:

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

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

回答by Charlie

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

如果您尝试选择 jquery 结果集,这是一个很好的解决方案

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