【问题标题】:How to set the default cursor caret in the middle of textarea/input vertically when on focus如何在焦点上垂直设置文本区域/输入中间的默认光标插入符号
【发布时间】:2016-02-09 05:55:05
【问题描述】:

我想知道如何使用 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>

【问题讨论】:

  • 现在说什么?也许包括您的意思的图像(以及您尝试过的任何代码)?

标签: javascript php jquery html css


【解决方案1】:

不太确定我明白你的要求,但无论如何这很有趣。这假定您要实际使用占位符文本并在中间插入插入符号。其次是尝试辨别您所说的“垂直”是什么意思。

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-15
    • 1970-01-01
    • 2022-01-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-17
    相关资源
    最近更新 更多