文本光标问题将字符插入可满足的元素时
有一个可满足的预元素。我想通过选项卡按钮添加选项卡字符。因此,我添加了称为puttab
的JS方法。此方法可以正常工作。但是文本光标有一个问题。 在正常键入时,视图不断向右转移。但是,当按下标签键时,视图不会在线路结束后继续向右滑动。然后,例如,当我按“ a”键时,我突然通过向右滑动而获得预期的视图。
我找不到有关在JS方法中添加字符后遵循文本光标的明确信息:
function putTab() {
var pre = document.getElementById("typearea");
var doc = pre.ownerDocument.defaultView;
var sel = doc.getSelection();
var range = sel.getRangeAt(0);
var tabNode = document.createTextNode(" ");
range.insertNode(tabNode);
range.setStartAfter(tabNode);
range.setEndAfter(tabNode);
sel.removeAllRanges();
sel.addRange(range);
}
document
.querySelector('button')
.addEventListener('click', putTab);
#typearea {
overflow-x: hidden;
margin: 8px;
max-height: auto;
white-space: pre;
display: block;
width: auto;
line-height: 1.5;
}
<button>Insert Tab</button>
<pre id="typearea" contenteditable>
Some predefined text.
</pre>
我希望我清楚地解释了这个问题,谢谢。
There is a pre element that is contenteditable. I wanted to add tab character via TAB button. So, I added js method called putTab
. This method works fine. But there is a problem about text cursor. While typing normally, the view is constantly shifting to the right. But when pressing the tab key, the view does not continue to slide to the right after the end of the line. Then, for example, when I press the 'A' key, I suddenly get the expected view by sliding to the right.
I could not find any clear information about following the text cursor after adding character in JS method:
function putTab() {
var pre = document.getElementById("typearea");
var doc = pre.ownerDocument.defaultView;
var sel = doc.getSelection();
var range = sel.getRangeAt(0);
var tabNode = document.createTextNode(" ");
range.insertNode(tabNode);
range.setStartAfter(tabNode);
range.setEndAfter(tabNode);
sel.removeAllRanges();
sel.addRange(range);
}
document
.querySelector('button')
.addEventListener('click', putTab);
#typearea {
overflow-x: hidden;
margin: 8px;
max-height: auto;
white-space: pre;
display: block;
width: auto;
line-height: 1.5;
}
<button>Insert Tab</button>
<pre id="typearea" contenteditable>
Some predefined text.
</pre>
I hope I explained the problem clearly, thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
由于OP提供的样式至少可以水平地滚动,因此在附加其他字符的过程中,需要再次将内容滚动到其父母的视图中。
因此,OP可以使用内容编辑的容器的
scrollto
方法。但是,再次,OP必须弄清楚何时(附加内容)和何时(例如,在光标仍然完全对齐时预先插入或插入内容)以应用此方法。但是,使用容器的
scrollby
方法涵盖了任何情况。Since the OP provides styling which makes the editable content scroll at least horizontally, the content, while appending additional characters to it, needs to be scrolled into its parent's view again.
Thus, the OP could use the content-editable container's
scrollTo
method. But then again the OP had to figure out when (appending content) and when not (e.g. prepending or inserting content while cursor is still perfectly aligned) to apply this method.But using the container's
scrollBy
method covers any scenario.