垂直居中的光标在textarea或可编辑的div中

时间:2011-12-19 15:14:15

标签: css vertical-alignment

是否可以将光标垂直居中放在textarea或editable div中。请参见附图。

enter image description here

1 个答案:

答案 0 :(得分:1)

好的,我使用了一些JavaScript来使它工作:

HTML:

<div id="test">
    <textarea autofocus></textarea>
</div>

CSS:

#test {
    width: 400px;
    height: 300px;
    line-height: 300px;
}

#test > textarea {
    display: inline-block;
    width: 100%;
    height: 1.4em;
    line-height: 1.4;
    border: none;
    resize: none;
    overflow: hidden;
    vertical-align: middle;
}

JavaScript的:

ta.onkeyup = function () {
    var n = this.value.match( /\n/g );

    if ( n ) {
        this.style.height = ( n.length + 1 ) * 1.4 + 'em';
    } else {
        this.style.height = '1.4em';
    }
};

现场演示: http://jsfiddle.net/SPpKY/show/

但是,只有在手动输入换行符时才有效...

相关问题