JavaScript获取选中文本 光标所在元素 令狐不聪 分享于 6分钟前 1396阅 0人收藏此代码,
好图网图标搜索引擎,提供超过60万的免费图标、PNG图标、ICO图标、ICNS图标、网页图标
JavaScript获取选中文本 光标所在元素
<!DOCTYPE HTML> <html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8"> <title>getSelection</title> <script type="text/javascript"> function GetSelectedText (){ var userSelection, ta; if (window.getSelection && document.activeElement){ if (document.activeElement.nodeName == "TEXTAREA" || (document.activeElement.nodeName == "INPUT" && document.activeElement.getAttribute("type").toLowerCase() == "text")){ ta = document.activeElement; userSelection = ta.value.substring(ta.selectionStart, ta.selectionEnd); } else { userSelection = window.getSelection(); } document.getElementById("seltext").innerHTML += "Selection="+userSelection.toString()+" [1]<br>"; } else { // all browsers, except IE before version 9 if (document.getSelection){ userSelection = document.getSelection(); document.getElementById("seltext").innerHTML += "Selection="+userSelection.toString()+" [2]<br>"; } // IE below version 9 else if (document.selection){ userSelection = document.selection.createRange(); document.getElementById("seltext").innerHTML += "Selection="+userSelection.text+" [3]<br>"; } } } </script> </head> <body onmouseup="GetSelectedText()"> <h1>Drag to select text (script runs on mouseup)</h1> <textarea rows="5" cols="30">Select text or part of it.</textarea><br> <input type="text" name="text1" value="Some more play text" size="50"><br> <div id="seltext"></div> </body> //该代码片段来自于:
标签:
相关代码片段: