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

标签 jquery html css

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

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>

如何解决这个问题?

感谢您的宝贵时间和帮助。

更新

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

最佳答案

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

希望这对您有所帮助。

关于jquery - 更新其中的html时,光标跳转到代码标签的开头,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33237493/

相关文章:

CSS - 滚动被后面的div消耗

javascript - 更改同一元素上多个单击事件的优先级

javascript - 通过查找子元素的 data-id 获取父元素的索引

javascript - 从列表中删除元素的更好方法?

javascript - jQuery next().addClass() 和 prev().addClass() 问题

jquery - 使用 jquery 将 CSS 添加到 iframe

html - 为什么 div 比 font-size 大?

html - 特定网站的 CSS 布局

html - header 和 div 出现在同一行

javascript - 获取图像 src 如果有多个则获取图像 src 只获取一张图像 src