Home >Web Front-end >JS Tutorial >Use javascript to get the cursor position in textarea_javascript skills
For people who write JavaScript and web page editors, obtaining the cursor position in a textarea is a very important issue, and many people are often at a loss in this area and cannot find a good way. Yesterday I found a piece of javascript code on the Internet. I didn't want to put the original version here because it was so exciting and I was afraid that I would change it, so I'll put the original version here.
var start=0;
var end=0;
function add(){
var textBox = document.getElementById("ta"); value.substr(0, start);
var post = textBox.value.substr(end);
textBox.value = pre document.getElementById("inputtext").value post;
}
function savePos(textBox){
//If it is Firefox (1.5), the method is very simple
if(typeof(textBox.selectionStart) == "number"){
start = textBox.selectionStart;
end = textBox.selectionEnd; 🎜> var range = document.selection.createRange();
if(range.parentElement().id == textBox.id){
var range = document.selection.createRange(); // create a selection of the whole textarea
var range_all = document.body.createTextRange();
range_all.moveToElementText(textBox);
range_all .compareEndPoints() compares two endpoints. If range_all is further to the left than range, then //Returns a value less than 0, then range_all moves a little to the right until the start of the two ranges is the same.
// calculate selection start point by moving beginning of range_all to beginning of range
for (start=0; range_all.compareEndPoints("StartToStart", range) range_all.moveStart('character', 1);
// get number of line breaks from textarea start to selection start and add them to start
// 计算一下
for (var i = 0; i if (textBox.value.charAt(i) == 'n')
start ;
}
// create a selection of the whole textarea
var range_all = document.body.createTextRange();
range_all.moveToElementText(textBox);
// calculate selection end point by moving beginning of range_all to end of range
for (end = 0; range_all.compareEndPoints('StartToEnd', range) range_all.moveStart('character', 1);
// get number of line breaks from textarea start to selection end and add them to end
for (var i = 0; i if (textBox.value.charAt(i) == 'n')
end ;
}
}
}
document.getElementById("start").value = start;
document.getElementById("end").value = end;
}
The following is how to call js code in the page: