获取浏览器中选中部分,比如文本等

代码如下:

效果如图

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>无标题文档</title>
 6     <script>
 7         
 8         function myfun(){
 9             // alert("b:"+window.b);
10             var obj = getTheSelected();
11             alert(obj);
12 
13         }
14         //获取选中的文本并返回
15         function getTheSelected(){
16             var txt;
17             //做能力检测,检查是IE还是非IE
18             if(document.selection) {
19                 txt = document.selection.createRange().text; // IE
20             } else {
21                 txt = document.getSelection();//非IE
22             }
23             return txt.toString();
24         }
25     </script>
26 </head>
27  
28 <body>
29     <div>请选中这里的部分文字。</div>  
30     <input type="text" value="我是默认值"/>
31     <img  src="wait.gif" />
32     <input type="button" value="dd" onclick="myfun();" />
33 </body>
34 </html>

更多的效果可以调试这个网页:http://www.techweb.com.cn/ihealth/2016-06-03/2342854.shtml

原文地址:https://www.cnblogs.com/Sunnor/p/5557851.html