This article describes the method of obtaining selected text that is compatible with various browsers. Share it for your reference, as follows:
The screenshot of the running effect is as follows:
The specific code is as follows:
<!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>Text selected</title><style type = "text/css"> #showSelected{ margin:100px auto; width:100%; height:200px; background:#ececec; border:1px solid #ccc; }</style><script type = "text/javascript">//Pass in the object to get the selected text function getSelectedText(e){ //Get the selection text under IE if (document.selection) { return document.selection.createRange().text; } //Get the selection text under firefox else if (window.getSelection().toString()) { return window.getSelection().toString(); } //Get the selection text of the input or textArea field under firefox 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 program for testing! </div> <div id = "showSelected"></div> </body></html>For more information about JavaScript related content, please check out the topics of this site: "Summary of JavaScript switching effects and techniques", "Summary of JavaScript search algorithm skills", "Summary of JavaScript animation effects and techniques", "Summary of JavaScript errors and debugging techniques", "Summary of JavaScript data structures and algorithm skills", "Summary of JavaScript traversal algorithms and techniques", and "Summary of JavaScript mathematical operations usage"
I hope this article will be helpful to everyone's JavaScript programming.