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

标签 javascript php jquery html css

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

相关文章:

javascript - 我的 jQuery 脚本不处理图像,但处理所有其他元素

javascript - 更新 reducer 中对象的状态

php - 在 PHP 中将 Firebird 与 MySQL 同步

php - register_shutdown_function无法捕获 fatal error : (Uncaught Error unset static property example, Call to undefined function prom())

javascript - 获取 FancyTree 中的焦点节点

javascript - 由于 JavaScript 延迟错误,图像 slider 无法工作

javascript - 动态向数据库插入数据

jquery - .serialize() 和 .serializeArray() 有什么区别?

php - 找不到消息类 'mongoclient' codeigniter

javascript - 如何同步单独 iframe 中的两个文本区域?