How can I detect when a line is automatically wrapped in a textarea?

后端 未结 2 563
忘掉有多难
忘掉有多难 2021-01-13 07:26

When typing text into a textarea and it becomes wider than the area, the text is wrapped onto the next line. Is there a way I can programmatically determine when this happen

2条回答
  •  情歌与酒
    2021-01-13 07:52

    You can measure every line width using a "hidden" span.
    If the line width is greater than the textarea width then the line is wrapped

    demo here

    function textWidth(txt, font, padding) {
        $span = $('');
        $span.css({
            font:font,
            position:'absolute',
            top: -1000,
            left:-1000,
            padding:padding
        }).text(txt);
        $span.appendTo('body');
        return $span.width();
    }
    

提交回复
热议问题