Create tooltip at cursor position in text area with jQuery

后端 未结 2 724
陌清茗
陌清茗 2021-01-18 11:59

I\'m trying to create a tooltip above the input caret in a text area. This would be easy if I could get the x,y coordinates of the caret in the text area, however I\'ve been

2条回答
  •  梦谈多话
    2021-01-18 12:34

    Hmmm I do not really see anything in jQuery events that will easily give you an x y coord for the caret.

    However there are quite a few ways for detecting the caret position in a text field:

    http://laboratorium.0xab.cd/jquery/fieldselection/0.1.0/test.html

    Is it possible to programmatically detect the caret position within a element?

    Caret position in textarea, in characters from the start

    Using this, you could try to estimate the pixel coordinates for the tool tip.

    If you want it to be more exact use a monospaced font inside of your text fields.

    //depending on size of font
    var charWidth = 10;
    //using any number of the above methods to get caret position
    var caretPosition = getCaretPos('#myTextField');
    var textFieldOffsetX = $('#myTextField').offset.left;
    var toopTipPositionX = caretPosition * charWidth + textFieldOffsetX;
    

    It is not exact and it is not going to be perfect, but it might be close enough.

提交回复
热议问题