最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jquery how to decrease number of cols in textarea based on content - Stack Overflow

programmeradmin2浏览0评论

I have a textarea with the default number of columns, like 10 or 15 or something. I want the text area to shrinkwrap the text inside on blur. Does anyone know how to do this?

So far I have

$('textarea').live('blur', function() {
    var textAreaWidth = $(this).val().length;
    $(this).attr('cols', 'textAreaWidth');

});

But this is ugly for obvious reasons. I just have no clue how to do this.

Any Ideas?

I have a textarea with the default number of columns, like 10 or 15 or something. I want the text area to shrinkwrap the text inside on blur. Does anyone know how to do this?

So far I have

$('textarea').live('blur', function() {
    var textAreaWidth = $(this).val().length;
    $(this).attr('cols', 'textAreaWidth');

});

But this is ugly for obvious reasons. I just have no clue how to do this.

Any Ideas?

Share Improve this question asked Apr 12, 2012 at 6:01 mharris7190mharris7190 1,3743 gold badges21 silver badges36 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 2

if you want to only decrease the size you should check that if the value is less than, say 20 and then decrease the number of columns. try this:

<textarea rows="2" cols="20"></textarea>

$('textarea').on('blur', function() {
    var textAreaWidth = $(this).val().length;

    if (textAreaWidth < 20) {
       $(this).attr('cols', textAreaWidth);
    }
    $('textarea').on('keypress', function() {
       $(this).attr('cols', '20');
    });   
});

http://jsfiddle/4bccm/

Remove the single quotes from around 'textAreaWidth' in

$(this).attr('cols', 'textAreaWidth');

This is a variable and doesn't need quotes around it.

$('textarea').bind('blur keyup', function() {
    $(this).attr('cols', $(this).val().length);
});​

This makes it shrink or grow as you type/blur.

发布评论

评论列表(0)

  1. 暂无评论