<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<title>微博插入话题的效果实现</title>
<linkrel="stylesheet"href="../css/demo.css"type="text/css"/>
<linkrel="stylesheet"href="../css/hl.css"type="text/css"/>
<style>
.textarea{
width:60%;
height:100px;
padding:3px;
font-size:1em;
}
</style>
</head>
<body>
<divid="main">
<divid="effect"class="part">
<h3>效果:</h3>
<divclass="show">
<divclass="demo">
<textareaid="textarea"class="textarea"></textarea>
<p>
<buttonid="button">插入话题</button>
</p>
</div>
</div>
</div>
</div>
</div>
<script>
varoButton=document.getElementById("button"),oTextarea=document.getElementById("textarea");
varTOPIC="插入话题";
varfunGetSelected=function(element){
if(!window.getSelection){
//IE浏览器
returndocument.selection.createRange().text;
}else{
returnelement.value.substr(element.selectionStart,element.selectionEnd-element.selectionStart);
}
},funInsertTopic=function(textObj){
vartopic="#"+TOPIC+"#",value=textObj.value,index=value.indexOf(topic);
if(index===-1){
//匹配
funTextAsTopic(textObj,topic);
}
value=textObj.value;
index=value.indexOf(topic);
if(textObj.createTextRange){
varrange=textObj.createTextRange();
range.moveEnd("character",-1*value.length)
range.moveEnd("character",index+5);
range.moveStart("character",index+1);
range.select();
}else{
textObj.setSelectionRange(index+1,index+5);
textObj.focus();
}
},funTextAsTopic=function(textObj,textFeildValue){
textObj.focus();
if(textObj.createTextRange){
varcaretPos=document.selection.createRange().duplicate();
document.selection.empty();
caretPos.text=textFeildValue;
}elseif(textObj.setSelectionRange){
varrangeStart=textObj.selectionStart;
varrangeEnd=textObj.selectionEnd;
vartempStr1=textObj.value.substring(0,rangeStart);
vartempStr2=textObj.value.substring(rangeEnd);
textObj.value=tempStr1+textFeildValue+tempStr2;
textObj.blur();
}
};
oButton.onclick=function(){
vartextSelection=funGetSelected(oTextarea);
if(!textSelection||textSelection===TOPIC){
//没有文字选中,光标处插入
funInsertTopic(oTextarea);
}else{
funTextAsTopic(oTextarea,"#"+textSelection+"#");
}
};
</script>
</body>
</html>