繁体   English   中英

更新其中的html时,光标跳转到代码标记的开头

[英]Cursor jumps to the start of code tag when updating html in it

当我输入我的代码标签并使用下面的脚本更新上下文时,它会继续将光标移动到代码框的开头。 我该如何解决?

 function HastTagLocation(Controll) { var controller = $('.' + Controll); controller.keyup(function() { // Get the code element. var e = $(this); // Get the text content. var text = e.text(); // Replace the matches and wrap them with span tag. var text = text.replace(/(\\![a-zA-Z]*)/g, '<span class="mark">$1</span>'); // Set the html of the original element. e.html(text); }); }; $(document).ready(function() { HastTagLocation('form-control'); }); 
 .hash { background-color: #808080; } 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" /> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <code class="form-control" id="test" contenteditable="true" style="height: 100%; min-height: 100px"></code> 

怎么可能解决这个问题?

谢谢你的时间和帮助。

UPDATE

解决方案不是让光标跳转到文本的末尾,而是让光标跳回到我最后写的东西

我认为一个解决方案是使用两个不同的元素,一个是您实际编写代码,一个是透明颜色,另一种是隐藏其内容,另一个是实际显示您想要显示的内容。

希望这可以帮助。

为了使其工作,您可以使用input事件而不是keyup (这样,即使按住键,它也会在每次输入后触发)。 然后使用SelectionRange对象相应地更改插入位置。 例如, Range具有setStartsetEnd方法,允许您将carret移动到特定位置。

有关这些对象的更高精度,请参阅: https//developer.mozilla.org/en-US/docs/Web/API/Rangehttps://developer.mozilla.org/en-US/docs/Web/API/选择 (请注意,这些对象上的某些功能仍在实验中)

以下是使用代码的快速示例。 请注意,这不是完全可操作的,为了使其正常工作,当感叹号生成元素时,您必须相应地进行调整以使插入符号处于正确的位置。 您还可能需要处理特定键输入(如SupprBackspace)与额外元素的交互。

 function HastTagLocation(Controll) { var controller = $('.' + Controll); controller.on('input', function (evt) { // Storing the caret state var sel, range, start, end ; sel = window.getSelection(); range = sel.getRangeAt(0); start = range.startOffset; end = range.endOffset; // Get the code element. var e = $(this); // Get the text content. var text = e.text(); // Replace the matches and wrap them with span tag. var text = text.replace(/(\\![a-zA-Z]*)/g, '<span class="mark">$1</span>'); // Set the html of the original element. e.html(text); // restoring the caret range.setStart(this.childNodes[0], start); range.setEnd(this.childNodes[0], end); }); }; $(document).ready(function () { HastTagLocation('form-control'); }); 
 .hash { background-color:#808080; } 
 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <code class="form-control" id="test" contenteditable="true" style="height: 100%; min-height: 100px"></code> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM