获取输⼊框光标位置及指定位置插⼊内容<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<script src="libs.baidu/jquery/1.9.0/jquery.js"></script>
</head>
<body>
<textarea name="" id="edit" cols="100" rows="10"></textarea>
<button οnclick="getPos()">获取光标位置</button>
<button οnclick="getSelect()">获取选中内容</button>
<button οnclick="insert()">插⼊⽂本</button>
<script>
$.extend($.fn,{
//获取⽂本框内光标位置
getSelectionStart: function() {
var e = this[0];
if (e.selectionStart) {
return e.selectionStart;
} else if (document.selection) {
e.focus();
var r=ateRange();
var sr = r.duplicate();
sr.setEndPoint('EndToEnd', r);
length - r.text.length;
}
return 0;
},
getSelectionEnd: function() {
var e = this[0];
if (e.selectionEnd) {
return e.selectionEnd;
} else if (document.selection) {
e.focus();
html内容文本框var r=ateRange();
var sr = r.duplicate();
sr.setEndPoint('EndToEnd', r);
length;
}
return 0;
},
//⾃动插⼊默认字符串
insertString: function(str) {
$(this).each(function() {
var tb = $(this);
tb.focus();
if (document.selection){
var r = ateRange();
pty();
< = str;
r.select();
} else {
var newstart = tb.get(0).selectionStart+str.length;
tb.val(tb.val().substr((0).selectionStart) +
str + tb.val().(0).selectionEnd));
<(0).selectionStart = newstart;
<(0).selectionEnd = newstart;
}
});
return this;
},
setSelection: function(startIndex,len) {
$(this).each(function(){
if (this.setSelectionRange){
this.setSelectionRange(startIndex, startIndex + len);
} else if (document.selection) {
var range = ateTextRange();
range.select();
} else {
this.selectionStart = startIndex;
this.selectionEnd = startIndex + len;
}
});
return this;
},
getSelection: function() {
var elem = this[0];
var sel = '';
if (document.selection){
var r = ateRange();
pty();
sel = r.text;
} else {
var start = elem.selectionStart;
var end = elem.selectionEnd;
var content = $(elem).is(':input') ? $(elem).val() : $(elem).text();                sel = content.substring(start, end);
}
return sel;
}
})
</script>
<script>
function getPos(){
alert($("#edit").getSelectionStart());
}
function getSelect(){
alert($("#edit").getSelection());
}
function insert(){
$("#edit").insertString("hello");
}
</script>
</body>
</html>

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。