前端技术

当前位置:首页 > 前端技术 >

文本域(Textarea)根据内容自动调整高度

时间:2015-06-13        阅读:次        QQ群:182913345

Js实现form表单中的文本域(Textarea)根据内容自动调整高度,代码如下:
 
HTML部分

<textarea data-adaptheight rows="3" cols="40" placeholder="Your input" style="padding:16px;line-height:1.5;"></textarea>

JS部分

(function() {
    function adjustHeight(textareaElement, minHeight) {
        // compute the height difference which is caused by border and outline
        var outerHeight = parseInt(window.getComputedStyle(el).height, 10);
        var diff = outerHeight - el.clientHeight;

        // set the height to 0 in case of it has to be shrinked
        el.style.height = 0;

        // set the correct height
        // el.scrollHeight is the full height of the content, not just the visible part
        el.style.height = Math.max(minHeight, el.scrollHeight + diff) + 'px';
    }

    // we use the "data-adaptheight" attribute as a marker
    var textAreas = document.querySelectorAll('textarea[data-adaptheight]');

    // iterate through all the textareas on the page
    for (var i = 0, l = textAreas.length; i < l; i++) {
        var el = textAreas[i];

        // we need box-sizing: border-box, if the textarea has padding
        el.style.boxSizing = el.style.mozBoxSizing = 'border-box';

        // we don't need any scrollbars, do we? 
        el.style.overflowY = 'hidden';

        // the minimum height initiated through the "rows" attribute
        var minHeight = el.scrollHeight;

        el.addEventListener('input', function() {
            adjustHeight(el, minHeight);
        });

        // we have to readjust when window size changes (e.g. orientation change)
        window.addEventListener('resize', function() {
            adjustHeight(el, minHeight);
        });

        // we adjust height to the initial content
        adjustHeight(el, minHeight);
    }
}());

上一篇:HTML表单详细讲解

下一篇:js中substr与substring的区别

扫一扫,更多精彩内容推送

PHP技术分享

分享PHP技术,前端技术,数据库,SEO优化,服务器,网络安全等知识,是php程序员工作学习的好帮手!

Copyright © 2013-2015.PHP技术分享 www.php520.cn  版权所有  网站地图    PHP学习交流群

免责声明:网站内容收集于互联网,本网站不承担任何由于内容的合法性及健康性所引起的争议和法律责任。

欢迎大家对网站内容侵犯版权等不合法和不健康行为进行监督和举报。 沪ICP备15014499号-2