在动态大小的文本区域中垂直居中占位符



我正在努力使占位符在文本区域中垂直居中。到目前为止,我发现的唯一可用方法是行高语句,但这不允许我将其集中放置在多种大小的文本区域中。

textarea {
height: 113px;
}
textarea::-webkit-input-placeholder {
color: #444;
font-weight: bold;
text-align: center;
line-height: 800%;
overflow: hidden;
}
<textarea placeholder="Some sample text."></textarea>

你的问题有点模糊。我假设您想垂直对齐占位符,无论用户将其大小调整多远。

当用户调整大小时,textarea不会触发resize事件,因此我将有趣的代码放在setInterval中。每秒十次将 css 变量--line-height设置为文本区域的高度。我这样做是因为无法在伪元素(::placeholder等(上设置 css。

浏览器支持 - 除IE11外,所有主流浏览器都支持var()

jQuery(function($) {
let $textarea = $('textarea');
setInterval(function() {
$textarea.get(0).style.setProperty("--line-height", $textarea.height() + 'px');
}, 100);
});
textarea {
height: 113px;
--line-height: 800%;
}
textarea::placeholder {
color: #444;
font-weight: bold;
text-align: center;
line-height: var(--line-height);
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea placeholder="Some sample text."></textarea>

只需使用文本 svg 作为背景图像并将其定位到中心即可。由于没有一个真正工作良好的:empty伪选择器,你可以使用:invalid来模拟占位符行为,如这篇文章所述:我可以用 CSS 选择空文本区域吗?

textarea:invalid {
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='74' height='13' viewBox='0 0 74 13'><text transform='matrix(1 0 0 1 0 10)' font-size='12'>Write text here</text></svg>");
background-position: center;
background-repeat: no-repeat;
}
<textarea required></textarea>

你可以用JavaScript和span元素来做到这一点。我在小提琴中创建一个简单的解决方案:

var txt = document.getElementById("txt");
var span = document.getElementById("span");
txt.onkeydown = function() {
if (txt.value == "") {
span.style.display = "block";
} else {
span.style.display = "none";
}
}
setInterval(()=>{
	span.style.top = String(parseInt(txt.style.height)/2) + "px";
}, 10)
textarea {
height: 113px;
}
span {
position: absolute;
top: 50px;
left: 10px;
color: #444;
font-weight: bold;
overflow: hidden;
}
<textarea id="txt" onresize="console.log('test')"></textarea>
<span id="span">Placeholder</span>

我认为没有其他选择

编辑 1:

对不起,我没有看到理查德·帕纳比-金的答案。但是现在您有 2 个示例;)1 个香草和 1 个带 JQuery

最新更新