JavaScript

textarea高度自适应,textarea随着内容高度变化

有时候我们需要textarea的高度随着内容的多少去自适应的变化,今天我使用了JS原生和JQ写了一个textarea的高度随着他的内容高度变化的代码,希望能帮上忙。

废话不多说直接贴代码:


<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<style>
    textarea{ width:500px; margin:20px auto; padding:0; font-size:14px; color:#333; font-family:"Microsoft YaHei"; line-height:28px;}
</style>
<div>
<textarea id="textarea">
    CGLweb前端  http://cenggel.com/
    青格勒前端博客  http://cenggel.com/
    CGLweb前端  http://cenggel.com/
    青格勒前端博客  http://cenggel.com/
</textarea>
</div>
<script type="text/javascript">
    $(document).ready(function () {
        var text_box = $('#textarea');
        function  cglHeight() {
            var cglTextHeight = text_box.get(0).scrollHeight;
            text_box.css('height',cglTextHeight+'px');
            console.log(cglTextHeight);
        };
        cglHeight();
        text_box.on('keyup mousedown mouseup focus blur',function(){
            cglHeight();
        });
    });
</script>

如果对你有帮助,别了分享哦。

0 条留言

去留言

还没有留言。

留下留言

请友善交流,评论可能需要审核后显示。