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

前端 未结 2 888
小蘑菇
小蘑菇 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

    0 讨论(0)
  • 2021-01-17 22:36

    Having that 15 is the line height, this works (tested in firefox):

    http://jsfiddle.net/h46jh/12/

    $("textarea").click(function (evt) {
      cursor_position = evt.pageY - $('textarea').offset().top;
      if (cursor_position <= 15) {
        alert("first line");
      } else {
        alert("other line");
      }
    });
    

    Credits:

    Find mouse position relative to element

    0 讨论(0)
提交回复
热议问题