1

我正在编写一些代码来在 contenteditable div 中查找用户选择,我从这篇 quirksmode 文章中获取我的代码。

function findSelection(){
  var userSelection;
  if (window.getSelection) {userSelection = window.getSelection;} 
   else if (document.selection){userSelection = document.selection.createRange();} // For microsoft
  if (userSelection.text){return userSelection.text} //for Microsoft
   else {return userSelection} 
  } 

我正在 Chrome 和 Firefox 中对其进行测试,如果我alert(userSelection)在函数内执行操作或在函数外执行 alert(findSelection();),它会返回function getSelection() {[native code]}. 如果我这样做console.log(findSelection();),它会给我getSelection()。是不是我做错了什么?

4

3 回答 3

3

getSelection 是一个函数……你需要执行它来获得选择吗?

if (window.getSelection) {userSelection = window.getSelection();}
于 2010-05-12T16:13:40.950 回答
1

将其更改为

  if (window.getSelection) {userSelection = window.getSelection();}

( getSelection())

于 2010-05-12T16:14:27.283 回答
0

这是为了获取选择的文本。即使错字已修复,您的行为也会不一致:IE 将选择的文本作为字符串返回,而其他浏览器将返回一个Selection对象,该对象仅在调用其toString()方法时才会为您提供选择文本字符串。

以下会更好:

function getSelectionText(){
    if (window.getSelection) {
        return "" + window.getSelection();
    } else if (document.selection && document.selection.createRange) {
        return document.selection.createRange().text;
    }
}
于 2010-05-13T08:59:12.083 回答