开发者

Determine if cursor position is on start of a defined row in textarea

How to determine if cursor p开发者_运维技巧osition is on start of a defined row in textarea with JavaScript?


Using the answer provided here:

Caret position in textarea, in characters from the start

you can get the offset of the cursor position in the text. After you have that, you can count the newline characters present in the text of the <textarea> before the offset to figure out which line you are on. If the offset is just after a newline, then you're at the start of the row. Using these two methods, you should be able to figure out if you are at the start of a specific line. For example:

var offset = getCaret('mytextarea');
var text = document.getElementById('mytextarea').value;
var line_number = 1;
var i;

for ( i = 0; i < offset; i++ ) {
    if ( text[i] == '\n' ) {
        line_number++;
    }
}

if ( !i || text[i-1] == '\n' ) {
    // You're at the start of a line
}

Note: IE might use carriage returns (\r) as well, so you may have to account for them.


You could use one or a combination of the on events: onchange, onkeyup, onkeydown, onkeypress.

Provide a little more detail on your overall goal.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜