我想知道如何使用 javascript/css 在两行占位符文本之间设置默认光标位置,以便用户输入可以在输入字段中垂直居中(我认为这看起来更好)。
下面的演示
<textarea id="topic_title_input" placeholder="Hi there, I want the cursor caret starts in the middle of these two lines (veritcally) when onfocus"></textarea>
<style>
#topic_title_input{
font-size: 20;
border-color: orange;
color:black;
background-color: white;
/*text-indent:10px;*/
border:1px solid orange;
width:521px;
height:60px;
outline:none;
border-radius:3px;
resize:none;
padding:7px;
}
</style>
不太确定我明白你在问什么,但无论如何都很有趣。这假定您希望实际使用占位符文本并在中间插入插入符号。其次是试图辨别你所说的"垂直"是什么意思。
var input = document.getElementById('topic_title_input');
var inputSpace = document.getElementById('topic_title_alt');
// Proof of concept. Will blow out existing text on each focus!
input.addEventListener('focus', updateTextArea);
inputSpace.addEventListener('focus', withBreak);
function updateTextArea(e) {
var value, pos;
value = input.getAttribute('placeholder');
// Put it anywhere you want
pos = value.indexOf('middle');
input.value = value;
// Normal browsers and IE9+:
input.setSelectionRange(pos, pos);
}
function withBreak(e) {
var value, pos, splitVal, newVal;
value = inputSpace.getAttribute('placeholder');
// Put it anywhere you want
pos = value.indexOf('middle');
newVal = value.substring(0, pos) + "rnrn";
newVal += value.substring(pos)
inputSpace.value = newVal;
// Normal browsers and IE9+:
inputSpace.setSelectionRange(pos + 1, pos + 1);
}
textarea {
font-size: 20;
border-color: orange;
color: black;
background-color: white;
/*text-indent:10px;*/
border: 1px solid orange;
width: 521px;
height: 60px;
outline: none;
border-radius: 3px;
resize: none;
padding: 7px;
}
<h2>Insert at "middle"</h2>
<textarea id="topic_title_input" placeholder="Hi there, I want the cursor caret starts in the middle of these two lines (veritcally) when onfocus"></textarea>
<h2>This kind of space?</h2>
<textarea id="topic_title_alt" placeholder="Hi there, I want the cursor caret starts in the middle of these two lines with a space (vertically) when onfocus"></textarea>