我想在文档中选择文本后调用函数。以下代码无效
var showSelWin = document.getElementById('innerwindow');
var txt = ' ';
if (document.getSelection) function(){
txt = document.getSelection();
showSelWin.innerHTML = txt;
document.body.insertBefore(showSelWin, document.body.firstChild);}
答案 0 :(得分:0)
document.getSelection方法在Google Chrome,Safari和Internet Explorer中的工作方式与Firefox和Opera相同。
它在Firefox和Opera中返回一个字符串,并在Google Chrome,Safari和Internet Explorer中返回selectionRange对象(document.getSelection方法与Google Chrome,Safari和Internet Explorer中的window.getSelection方法相同)。 / p>
在Firefox 9,Opera,Google Chrome,Safari和Internet Explorer 9中,使用window.getSelection方法和window.getSelection方法返回的selectionRange对象的toString方法来获取所选内容的文本内容。 / p>
在较旧的Internet Explorer版本中,使用选择对象的createRange方法和createRange方法返回的TextRange对象的text属性来获取选择的文本内容。
适合您的工作样本:http://jsfiddle.net/uX628/
function GetSelectedText () {
if (document.getSelection) { // all browsers, except IE before version 9
var sel = document.getSelection ();
// sel is a string in Firefox and Opera,
// and a selectionRange object in Google Chrome, Safari and IE from version 9
// the alert method displays the result of the toString method of the passed object
alert (sel);
}
else {
if (document.selection) { // Internet Explorer before version 9
var textRange = document.selection.createRange ();
alert (textRange.text);
}
}
}