window.getSelection和document.selection getSelection

window.getSelection和document.selection

 返回一个 Selection 对象,表示用户选择的文本。
  • selection 是一个 Selection 对象。 如果想要将 selection 转换为字符串,可通过连接一个空字符串("")或使用 String.toString() 方法。
IE9以下支持:document.selection   
 IE9、Firefox、Safari、Chrome和Opera支持:window.getSelection() 
 
alert 选中的内容
html:
<div>你选中我之后,弹出我!逗你玩</div>
js1:
function test(){
var txt = window.getSelection?window.getSelection():document.selection.createRange().text;
alert(txt)
}
document.onmouseup = test
 
移除选中内容:
html:
<div>你不能选中我,不信你试试</div>
js2:
function test(){
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
}
document.onmouseup = test
爱设计,爱代码,爱生活
原文地址:https://www.cnblogs.com/abby-WebDeveloper/p/6294077.html