有没有办法让文本框自动扩展而不使用jQuery?

时间:2016-08-03 08:33:46

标签: html css css3

我已将resize设置为vertical,但我希望当用户填充文本框时,其大小会向下扩展。如果不使用像jQuery这样的外部库,有没有办法可以做到这一点?

2 个答案:

答案 0 :(得分:4)

仅限CSS和contentEditable="true"属性。

div {
display:inline-block;
border: solid 1px #000;
min-height: 200px;
width: 300px;
}

Demo Here

答案 1 :(得分:1)

这已在此处得到解答:Creating a textarea with auto-resize

<!DOCTYPE html>
<html>
<head>
<title>autoresizing textarea</title>
<style type="text/css">
textarea {
    border: 0 none white;
    overflow: hidden;
    padding: 0;
    outline: none;
    background-color: #D0D0D0;
    resize: none;
}
</style>
<script type="text/javascript">
var observe;
if (window.attachEvent) {
    observe = function (element, event, handler) {
        element.attachEvent('on'+event, handler);
    };
}
else {
    observe = function (element, event, handler) {
        element.addEventListener(event, handler, false);
    };
}
function init () {
    var text = document.getElementById('text');
    function resize () {
        text.style.height = 'auto';
        text.style.height = text.scrollHeight+'px';
    }
    /* 0-timeout to get the already changed text */
    function delayedResize () {
        window.setTimeout(resize, 0);
    }
    observe(text, 'change',  resize);
    observe(text, 'cut',     delayedResize);
    observe(text, 'paste',   delayedResize);
    observe(text, 'drop',    delayedResize);
    observe(text, 'keydown', delayedResize);

    text.focus();
    text.select();
    resize();
}
</script>
</head>
<body onload="init();">
<textarea rows="1" style="height:1em;" id="text"></textarea>
</body>
</html>

示例:https://jsfiddle.net/hmelenok/WM6Gq/

致信panzi,在此投票:https://stackoverflow.com/a/5346855/1540350