gpt4 book ai didi

javascript - 如何在焦点上垂直设置文本区域/输入中间的默认光标插入符

转载 作者:行者123 更新时间:2023-11-28 06:26:03 25 4
gpt4 key购买 nike

我想知道如何使用 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) + "\r\n\r\n";
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>

关于javascript - 如何在焦点上垂直设置文本区域/输入中间的默认光标插入符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35279073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com