使用window.getSelection获取字符串

nXq*_*Xqd 2 javascript

我正在尝试使用window.getSelection获取字符串但它返回一个对象.

var text = '';
text = document.getSelection();
alert(typeof(text)); //object
Run Code Online (Sandbox Code Playgroud)

ken*_*ytm 8

.getSelection()返回一个DOMSelection对象.该DOMSelection类包含一个.toString()把它变成一个字符串的方法.

所以

var str = window.getSelection().toString();
alert(typeof(str));  // string.
Run Code Online (Sandbox Code Playgroud)