我有一些代码返回选择的文本,我可以将该字符串分配给一个变量,但现在我需要的是两个变量,一个用于选择前的文本,另一个用于选择后的文本。 下面是获得选择的代码:Javascript:我可以得到一个选择的文本,现在如何获得选择之外的文本?
function findSelection(){ //returns the selection object.
var userSelection;
if (window.getSelection) {userSelection = window.getSelection();} // Mozilla Selection object.
else if (document.selection){userSelection = document.selection.createRange();} //gets Microsoft Text Range, should be second b/c Opera has poor support for it.
if (userSelection.text){return userSelection.text} //for Microsoft Objects.
else {return userSelection} //For Mozilla Objects.
}
然后我找到anchorOffset和focusOffset找到插入符号位置。我试着用这些修改的范围对象,像这样:
var range = document.createRange();
range.setStart(textdiv,0);
range.setEnd(textdiv,5);
凡textdiv
是一个变量抱着最后一个div用户点击。问题是Firefox只是给我一个"Security error" code: "1000"
在线range.setStart(textdiv,0);
。
有没有更简单的方法去做到这一点?我真的只需要文字,没有什么更多。
这'findSelection'功能是有缺陷的,正如我在(显然忽略)答案解释你的关于这段代码的问题:http://stackoverflow.com/questions/2820650/javascript-functions-return-lines-of-function-code-or-native-code-what-am/2825473#2825473 – 2010-05-14 10:04:41