Test if cursor is on the first line in a textarea (with soft-newlines)

前端 未结 2 887
小蘑菇
小蘑菇 2021-01-17 21:32

Given a textarea with content that flows like this

     ––––––––––––––––––––––––––
    | This is some text, which |
    | wraps like this.         |
     ––––––––         


        
2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 22:21

    I only know of one "working method". The method requires use of textarea's "cols" attribute. Long story short, set the cols to the width you want, then divide the cursor position and floor it to see if it is less than 1, thus it = line 1!

    Might be easier to explain if I just show you a code example.

    $("textarea").live("keyup", function(e) {
        if ($("textarea").attr("cols")) {
            var cols = parseInt($("textarea").attr("cols")),
                curPos = $('textarea').prop("selectionStart"),
                result = Math.floor(curPos/cols);
            var msg = (result < 1) ? "Cursor is on the First line!" : "Cursor is on the line #"+(result+1);
            console.log($("p").text(msg).text());
        };
    });​
    

    however, this may still require some wired math as some col sizes may still say "line 2" when the cursor is simply at the END of line one (which technically would still be right since any character would drop to line 2)

    jsFiddle

提交回复
热议问题