js獲取選中文字值的例項程式碼

antzone發表於2017-03-15

在某些應用下,需要獲取選中文字的內容,下面就通過程式碼例項簡單介紹一下如何實現此功能。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>獲取選中的文字的內容-螞蟻部落</title>
<style type="text/css">
body{font-size:12px;}
#show{
  background-color:#CCFF99;
  width:300px;
  display:none;
}
</style>
<script type="text/javascript">   
String.prototype.trim=function(){    
  return this.replace(/^\s+|\s+$/g, "");    
} 
function getSelectText(id){
  var t=document.getElementById(id);
  if(window.getSelection) {
    if(t.selectionStart!=undefined&&t.selectionEnd!=undefined) {
      return t.value.substring(t.selectionStart,t.selectionEnd);
    } 
    else {
      return "";
    }
  } 
  else {
    return document.selection.createRange().text;
  }
}
window.onload=function(){
  var bt=document.getElementById('btn');
  var oshow=document.getElementById("show");
  bt.onclick=function(){
    oshow.style.display="block";
    oshow.innerHTML=getSelectText('content');
  }  
}
</script>
</head>
<body>   
<textarea id="content" cols="30" rows="10">螞蟻部落歡迎您,只有努力才會有美好的未來</textarea>   
<button id="btn">獲取選中值</button>
<div id="show"></div>
</body>   
</html>

相關文章