简体   繁体   中英

Adapt width of texture to its content

I need to adapt the width of a textarea (='#overlay') to its content. The minimum width should be 100px:

'input #overlay': function(e) {
    var overlay = $('#overlay'),
        element = document.getElementById('overlay'),
        pos     = overlay.position(),
        width   = 100;

    if (element.scrollWidth > element.clientWidth) {
        var diff  = Math.ceil((element.scrollWidth - element.clientWidth)/20)*20,
            left  = pos.left - (diff/2);
            width = element.scrollWidth + diff;

        overlay.css({left: left, width: width});
    }

This code works to expand the textarea if there is a long line. But it can't be used to make it smaller if you delete some characters of the line.

You have to set the minimum value before the if-part:

overlay.css({ width: 100 });

Then the height will always be adapted to the needed height.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM