標籤:js javascript cookie 表單 文本域
<pre class="javascript" name="code">
var fm = document.getElementsByTagName('form')[0];
var button = document.getElementsByName("button");
//擷取一個cookie的值function getCookie(index){var allcookies = document.cookie; var cookie_pos = allcookies.indexOf(index);if (cookie_pos != -1){cookie_pos += index.length + 1;var cookie_end = allcookies.indexOf(";",cookie_pos); if (cookie_end == -1){ cookie_end = allcookies.length; } var value = unescape(allcookies.substring(cookie_pos, cookie_end)); } return value; }//擷取文本中的游標位置 function getCursortPosition (ctrl) {var CaretPos = 0;// IE Supportif (document.selection) {ctrl.focus ();var Sel = document.selection.createRange ();Sel.moveStart ('character', -ctrl.value.length);CaretPos = Sel.text.length;}else if (ctrl.selectionStart || ctrl.selectionStart == '0')CaretPos = ctrl.selectionStart;return (CaretPos);}
//擷取文本游標位置並設定一個cookie來儲存游標時時變動的位置的函數var textpos = 0;textcontent.onclick = function(){textpos = getCursortPosition (textcontent);document.cookie="textpos="+textpos;textpos = getCookie("textpos");}//字串的寫入函數function content(string){s = textcontent.value;fm.content.value = s.substring(0,getCookie("textpos"))+string+s.substring(getCookie("textpos"));}
<pre class="php" name="code">//點擊按鈕向表單中的文本域的游標處新增內容button[0].onclick = function(){content('[b][/b]');}