您的位置:首页 > Web前端 > JavaScript

js从text或textarea文本框中选择部分文本,并取得选择的内容

2012-10-16 11:42 274 查看
亲测通过,兼容所有浏览器!

腾讯微博:http://t.qq.com/guyue1106/profile?pgv_ref=im.minicard.title&ptlang=2052

新浪weibo:http://weibo.com/1714234642/profile?leftnav=1&wvr=3.6&mod=personinfo

欢迎互加!

 

html:

<input type = "text" id = "textbox" value = "this is a textInput" />

首先是js从文本框中选择部分文本:

js:

function $$(id){
return document.getElementById(id);
}
function textSelect(textBox,start,end){
if(textBox.setSelectionRange){
textBox.setSelectionRange(start,end);
}else if(textBox.createTextRange){
var rang = textBox.createTextRange();
rang.collapse(true);
rang.moveStart('character',start);
rang.moveEnd('character',end-start);
rang.select();
}
textBox.focus();
}
textSelect($$('textbox'),3,7);
下面是js获取选中的内容

function getSelect(textBox){
if(textBox.selectionStart){
return textBox.value.substring(textBox.selectionStart,textBox.selectionEnd);
}else if(document.selection){
return document.selection.createRange().text;
}
}
alert(getSelect($$('textbox')));
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐