简体   繁体   English

在Javascript中按范围设置选择

[英]Set selection by range in Javascript

I want to select text by sending location/anchorOffset and length/offset using Javascript Here is my code 我想通过使用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);

But the issue is with range.setStart and range.setEnd its not working as I expect 但问题在于range.setStart和range.setEnd它没有像我预期的那样工作

The setStart() and setEnd() methods of DOM Range are well specified, so you could find the answer by reading the spec or 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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM