奇怪的行为与range.toString()(Strange behaviour with range.toString())

其他开发 IT屋
问 题

I want to get back the text that I select in an element using the Range object provided by Mozilla's flavour of javascript.

So I do this:

//assume that I'm only using Firefox, and there is just one selection
var range = window.getSelection().getRangeAt(0);
var rangeText = range.toString();

This works OK when the html of the selected text doesn't have any newlines In other words, if I have the following html:

<div>One. Two. Three. Four. Five.</div>

and I select Two. Three. Four., then everything is fine.

On the other hand, if I have

<div>
One.
Two.
Three.
Four.
Five.
</div>

and I select Two. Three. Four. as before, there are newlines introduced into the result returned from Range.toString(); the newlines are after Two., Three., and Four.

Obviously, when displayed in the browser, both html fragments are identical. Is there a way I can ensure that the same text is returned without newlines?

解决方案

OK, I used part of the answer from Tim Down in the end:

  var sel = window.getSelection();
  var range = sel.getRangeAt(0);
  var range2 = range.cloneRange();

  //do some stuff with range2...

  var rangeText, range2Text;

  sel.removeAllRanges();
  sel.addRange(range);
  rangeText = sel.toString();

  sel.removeAllRanges();
  sel.addRange(range2);
  range2Text = sel.toString();

本文地址:IT屋 » Strange behaviour with range.toString()

问 题

我想找回使用由Mozilla的javascript提供的Range对象在元素中选择的文本。所以我这样做:

>

  //假设我只使用Firefox,并且只有一个选择
var range = window.getSelection() .getRangeAt(0);
var rangeText = range.toString();


当所选文本的html没有任何换行符时,这可以正常工作换句话说,if我有以下的html:



 < div>一。二。三。四。五个< / DIV> 


我选择二。三。四。,那么一切都很好。

另一方面,如果我有

 < DIV> 
一个。
二。
三。
四。
五。
< / div>


我选择二。三。四。和以前一样,在从Range.toString()返回的结果中引入了换行符。换行符是 2。三。四。 显然,当在浏览器中显示时,两个html片段是相同的。有没有办法,我可以确保没有换行返回相同的文本?


解决方案

好的,我用部分答案Tim Down最后:

  var sel = window.getSelection(); 
var range = sel.getRangeAt(0);
var range2 = range.cloneRange();

//用range2 ...做一些东西...

var rangeText,range2Text;

sel.removeAllRanges();
sel.addRange(range);
rangeText = sel.toString();

sel.removeAllRanges();
sel.addRange(range2);
range2Text = sel.toString();

本文地址:IT屋 » 奇怪的行为与range.toString()