本文實例講述了JS實現兼容各種瀏覽器的獲取選擇文本的方法。分享給大家供大家參考,具體如下:
運行效果截圖如下:

具體代碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN""http://www.w3.org/TR/html4/strict.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>文本被選中</title><style type = "text/css"> #showSelected{ margin:100px auto; width:100%; height:200px; background:#ececec; border:1px solid #ccc; }</style><script type = "text/javascript">//傳入要獲取其中選擇文本的對象function getSelectedText(e){ //IE下獲取選擇文本 if (document.selection) { return document.selection.createRange().text; } //firefox下獲取選擇文本 else if (window.getSelection().toString()) { return window.getSelection().toString(); } //firefox下獲取input或textArea域的選擇文本 else if (e.selectionStart != undefined && e.selectionEnd != undefined) { var start = e.selectionStart; var end = e.selectionEnd; return e.value.substring(start, end); }}document.onmouseup = function(){ var ta = document.getElementById("myDiv"); document.getElementById("showSelected").innerHTML = getSelectedText(document.body);}</script></head> <body> <div id="myDiv"> This is a prograph for testing! </div> <div id = "showSelected"></div> </body></html>更多關于JavaScript相關內容感興趣的讀者可查看本站專題:《JavaScript切換特效與技巧總結》、《JavaScript查找算法技巧總結》、《JavaScript動畫特效與技巧匯總》、《JavaScript錯誤與調試技巧總結》、《JavaScript數據結構與算法技巧總結》、《JavaScript遍歷算法與技巧總結》及《JavaScript數學運算用法總結》
希望本文所述對大家JavaScript程序設計有所幫助。
新聞熱點
疑難解答