I don’t know how to write JS, but I know how to search, and here I found some things written by others:
select(document, tanchu);
/*=select[[
*
* Cross-browser selected text event
* @param
* object o DOM object that responds to the selected event, required
* function fn(sText,target,mouseP) callback function when the selected text is not empty, required
* |-@param
* |-sText selected text Content
* |-target element that triggered the mouseup event
* |-mouseP mouse coordinates when the mouseup event was triggered
*/
function select(o, fn){
o.onmouseup = function (e){
var event = window.event || e;
var target = event.srcElement ? event.srcElement : event.target;
if (/input|textarea/i.test(target .tagName) && /firefox/i.test(navigator.userAgent)) {
//Firefox selects text in the text box
var staIndex=target.selectionStart;
var endIndex=target.selectionEnd;
if(staIndex!=endIndex){
var sText=target.value.substring(staIndex,endIndex);
fn(sText,target);
}
}
else{
//Get the selected text
var sText = document.selection == undefined ? document.getSelection().toString():document.selection.createRange().text;
if (sText != " ") {
//Pass the parameters into the callback function fn
fn(sText, target);
}
}
}
}
/*]]select= */
function tanchu(txt,tar){
alert("The text belongs to the " tar.tagName " element, the selected content is: " txt);
}
Original See the author: http://momomolice.com/wordpress/archives/420.html
Attachment: The code to only get the selected text (does not respond to this event)
function getSelectedText()
{
if (window.getSelection)
{ // This technique is the most likely to be standardized.
// getSelection() returns a Selection object, which we do not document.
return window.getSelection().toString();
}
else if (document.getSelection)
{
// This is an older, simpler technique that returns a string
return document.getSelection();
}
else if ( document.selection)
{
// This is the IE-specific technique.
// We do not document the IE selection property or TextRange objects.
return document.selection.createRange(). text;
}
}
The selected text will be returned after the function is run.
The original author is no longer available. . .