【问题标题】:How to restore caret position in Javascript?如何在Javascript中恢复插入符号位置?
【发布时间】:2020-02-05 07:45:07
【问题描述】:

我正在尝试实现,当用户按下重置按钮时,光标会回到输入的开头。

谁能指导我如何实现这一目标?

function restore(){
    // here need to set the position
};
p {
  text-align:left;
  padding:10px;
  font-size: 20px;
  font-family: "Open Sans";
  border:1px black solid;
}

button{
 font-size: 25px;
}
<p contenteditable="true"></p>

<button onclick="restore()">Restore</button>

【问题讨论】:

标签: javascript html css


【解决方案1】:

您可以使用RangeSelection 对象,如this answer 中所述:

function restore() {
  var el = document.getElementById("editable");
  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(el, 0);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
}
p {
  text-align:left;
  padding:10px;
  font-size: 20px;
  font-family: "Open Sans";
  border:1px black solid;
}

button{
 font-size: 25px;
}
<p id="editable" contenteditable="true"></p>

<button onclick="restore()">Restore</button>

【讨论】:

    【解决方案2】:

    如果你可以使用 Input 标签代替 P 标签,这个代码是合适的:

    function myFunction() {
      var text = document.getElementById("myInput");
      text.select();
      text.setSelectionRange(text.value.length, text.value.length)
    }
    button{
     font-size: 25px;
    }
    <input type="text" value="hello" id="myInput">
    <button onclick="myFunction()">Copy text</button>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-02
      • 1970-01-01
      • 1970-01-01
      • 2016-11-08
      • 1970-01-01
      相关资源
      最近更新 更多