標籤:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>楓芸志 » 在文字框的指定位置插入文本並定位游標</title><script type="text/javascript"> function InsertString(tbid, str){ var tb = document.getElementById(tbid); tb.focus(); if (document.all){ var r = document.selection.createRange(); document.selection.empty(); r.text = str; r.collapse(); r.select(); } else{ var newstart = tb.selectionStart+str.length; tb.value=tb.value.substr(0,tb.selectionStart)+str+tb.value.substring(tb.selectionEnd); tb.selectionStart = newstart; tb.selectionEnd = newstart; }}function GetSelection(tbid){ var sel = ‘‘; if (document.all){ var r = document.selection.createRange(); document.selection.empty(); sel = r.text; } else{ var tb = document.getElementById(tbid); // tb.focus(); var start = tb.selectionStart; var end = tb.selectionEnd; sel = tb.value.substring(start, end); } return sel;}function ShowSelection(tbid){var sel = GetSelection(tbid); if (sel) alert(‘選中的文本是:‘+sel); else alert(‘未選擇文本!‘);}</script></head><body> <form><textarea id="txtContent" cols="50" rows="5">先在本文框中點擊滑鼠或選擇文本以確定游標位置和選取內容。</textarea><br /><br /> <input type = "button" value = "插入字串 {Good}" onclick="InsertString(‘txtContent‘, ‘{Good}‘);"/> <input type = "button" value = "插入字串 {Bad}" onclick="InsertString(‘txtContent‘, ‘{Bad}‘);"/> <input type = "button" value = "擷取選中的文本" onclick="ShowSelection(‘txtContent‘);"/><br /> <div id="tip"></div> </form> </body></html>
【Javascript】在文字框游標處插入文字並定位游標 (轉)