I'm trying to read in the value of selected text within a text area. Here is my code:
function readSelected(id)
{
textarea = document.getElementById(id);
if (document.selection)
{ //Code for IE
textarea.focus();
sel = document.selection.createRange();
alert(sel.text);
}
else
{ // Code for Mozilla Firefox
var len = textarea.value.length;
var start = textarea.selectionStart;
var end = textarea.selectionEnd;
var scrollTop = textarea.scrollTop;
var scrollLeft = textarea.scrollLeft;
sel = textarea.value.substring(start, end);
alert(sel);
}
}
HTML:
<textarea id="txt1" rows="10"></textarea>
<a onclick="readSelected('txt1');">Get Selected</a>
When you click the button, a popup should occur telling you what the selected text is.
The code works in Firefox, but I can't get it to work in IE8.
The problem is that clicking on the <a>
element destroys the selection. You could use an unselectable button instead:
<input type="button" value="get" onclick="readSelected('txt1');" unselectable="on">
There are other minor issues with your code
sel
and textarea
are the offenders here. scrollTop
and scrollLeft
are redundant. selectionStart
and selectionEnd
properties first, since they're the standard (HTML 5 specifies them and IE 9 will support them). Here's my rewritten version:
function readSelected(id) {
var sel = "", el = document.getElementById(id);
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
sel = el.value.slice(el.selectionStart, el.selectionEnd);
} else if (document.selection && document.selection.createRange) {
el.focus();
sel = document.selection.createRange().text;
}
alert(sel);
}
您是否尝试过onmousedown
而不是onclick
?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.