我试图找到一个解决方案,使文本在水平和垂直居中的textarea中键入.水平工作正常,text-align: center;
但垂直居中更麻烦.似乎解决方案是使用填充,但是当文本高达3行时,文本不再居中.在下面的小提琴中,我放置了一条红线,这是我的文本区域的中心.我需要它作为文本出现的中心.即使它是1,2,3,4或五行高.因此,如果我有4行文本,则红线需要位于第2行和第3行之间.
我想知道是否可能没有与jquery有关的工作?
Ric*_*ock 10
我想出了一个非常简单的解决方案,它会在您键入时修改顶部填充.
padding-top
应始终平等height/2 - font-size
.另外,使用box-sizing:border-box; 避免应用于textarea元素的默认样式的问题.
jQuery的
$('.mytext').on('input', function() {
var h= this.offsetHeight;
$(this).css({ //clear current padding and height so we can use scrollHeight below
paddingTop: 0,
height: 0
});
$(this).css({
paddingTop: Math.max(0, h/2 - this.scrollHeight/2),
height: h
});
});
Run Code Online (Sandbox Code Playgroud)
$('.mytext')
.on('input', function() {
var h = this.offsetHeight;
$(this).css({
paddingTop: 0,
height: 0
});
$(this).css({
paddingTop: Math.max(0, h / 2 - this.scrollHeight / 2),
height: h
});
})
.trigger('input')
.focus();
Run Code Online (Sandbox Code Playgroud)
.mytext {
resize: none;
width: 280px;
height: 150px;
font-size: 20px;
text-align: center;
box-sizing: border-box;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="mytext" placeholder="type text here"></textarea>
Run Code Online (Sandbox Code Playgroud)
看看这段代码片段,它可能会解决您的问题:
http://codepen.io/desandro/pen/gICqd
它依赖于 CSS 和包装器 div :
#wrap {
width: 50%;
position: relative;
font-family: sans-serif;
height: 70%;
border: 2px solid red;
}
#wrap .area {
resize: none;
outline: none;
border: 2px solid;
display: block;
width: 100%;
padding: 0;
position: absolute;
top: 0;
font-family: sans-serif;
font-size: 20px;
text-align: center;
}
#wrap textarea.area {
left: 0;
height: 100%;
border: 2px dotted blue;
background: transparent;
}
#wrap .dummy {
left: 100%;
}
Run Code Online (Sandbox Code Playgroud)