插入话题
<!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=gb2312" />
<title>插入话题</title>
</head>
<body>
<style type="text/css">
textarea{ 500px; height:200px;}
</style>
<script>
window._isIE = (navigator.appName == "Microsoft Internet Explorer");
if(window._isIE) {
if(navigator.userAgent.indexOf("Opera")>-1) window._isIE = null;
if(navigator.userAgent.indexOf("Windows NT 6.0")>-1) window._isVista = true;
else window._isVista = false;
}
else {
if(navigator.userAgent.indexOf("Gecko")==-1) window._isIE = null;
}
function setCursor(oElement, pos, len) {
var range = oElement.createTextRange();
range.collapse(true);
range.moveStart("character", pos + 1);
range.moveEnd("character", len - 2);
range.select()
};
function storeCaret (textEl) {
if (textEl.createTextRange){textEl.caretPos = document.selection.createRange().duplicate();}
}
//插入话题
function insertTopics(textareaID,sValue){
var oElement=document.getElementById(textareaID);
if (window._isIE) {
if (oElement.createTextRange && oElement.caretPos) {
var caretPos = oElement.caretPos;
caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == " " ? sValue+ " " : sValue
} else {
oElement.value += sValue
}
setCursor(oElement, oElement.value.indexOf(sValue),sValue.length)
} else {
if (oElement.setSelectionRange) {
var rangeStart = oElement.selectionStart;
var rangeEnd = oElement.selectionEnd;
var tempStr1 = oElement.value.substring(0, rangeStart);
var tempStr2 = oElement.value.substring(rangeEnd);
oElement.value = tempStr1 + sValue + tempStr2;
oElement.setSelectionRange(tempStr1.length+1, tempStr1.length+sValue.length-1)
} else {
oElement.value += sValue
}
var textIndex = oElement.value.indexOf(sValue);
oElement.setSelectionRange(textIndex+1, textIndex+sValue.length-1)
oElement.focus();
}
}
</script>
<textarea id="textareaID" onselect="storeCaret(this);" onclick="storeCaret(this);" onkeyup="storeCaret(this);"></textarea><a href="#" onclick="insertTopics('textareaID','#请在这里输入自定义话题#')">插入话题</a>
</body>
</html>