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

来源:互联网 发布:微信加粉软件靠谱吗 编辑:程序博客网 时间:2024/05/16 14:33

亲测通过,兼容所有浏览器!

腾讯微博: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')));



原创粉丝点击