<pre class="javascript" name="code">
var fm = document.getElementsByTagName('form')[0];
var button = document.getElementsByName("button");
var textcontent = document.getElementById('textcontent');
//获取一个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 Support
if (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]');
}