gpt4 book ai didi

javascript - 突出显示关键字的文本区域 : strange cursor behavior

转载 作者:行者123 更新时间:2023-11-29 17:48:24 24 4
gpt4 key购买 nike

我正在使用 Summernote插件创建一个漂亮的文本区域和Mark.js用于突出显示该文本区域内定义的关键字(例如 foo)的插件。

我有这个 HTML 代码:

<div id="text"></div>

和 Javascript 代码:

$('#text').summernote({
height: 150,
callbacks: {
onChange: function (contents, $editable){
$('.note-editable').unmark({"done": function () {
$('.note-editable').mark(
'foo',
{'separateWordSearch': false })
}})
}
}
}
);

JSFiddle

而且效果很好。每次用户在文本区域中写入 foo 时,单词都会突出显示,但我遇到了这个问题:当用户写入 foo 时,光标移动到 foo 字,我不想要这个。我该如何解决这个问题?

最佳答案

可编辑的 div(s) 不是处理输入的理想类型。类似的游标行为在使用 JS 或 jQuery 显式更新可编辑 div 的值时很常见。要解决这个问题,您要么需要使用合适的默认输入类型,例如 <input><textarea>标签。

这并不能解决您的用例,因为您将无法更改所选文本的属性。所以客户端的解决方案如下:

  1. 为每个这样的可编辑 div 创建一个全局变量来存储光标的更新值。
  2. 在每个 onblur 事件上更新这个全局变量的值。
  3. 在突出显示关键字之前检索此全局值。
  4. 在突出显示必要的关键字后,将光标更新为检索到的值。

以下是检索和更新游标值的函数:

function doGetCaretPosition (id, storeTo) {
var oField = document.getElementById(id);
// Initialize
var iCaretPos = -1;

// IE Support
if (document.selection) {

// Set focus on the element
oField.focus();

// To get cursor position, get empty selection range
var oSel = document.selection.createRange();

// Move selection start to 0 position
oSel.moveStart('character', -oField.value.length);

// The caret position is selection length
iCaretPos = oSel.text.length;
}

// Firefox support
else if (oField.selectionStart || oField.selectionStart == '0')
iCaretPos = oField.selectionStart;

// Return results
if( window[storeTo] !== undefined || window[storeTo] !== '' )
{
//if position is not updated
if( $(oField).val().length == iCaretPos )
window[storeTo] = -1;
else
window[storeTo] = iCaretPos;
console.log("[doGetCaretPosition Updated] "+$(oField).attr('id')+" in : "+window[storeTo]);
}
else
console.log("[doGetCaretPosition : failed]");
}


//Set caret position
function setCaretPosition(elemId, caretPos) {
var elem = document.getElementById(elemId);

if(elem != null) {
if(elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', window[caretPos]);
range.select();
}
else {
if(elem.selectionStart) {
elem.focus();
elem.setSelectionRange(window[caretPos], window[caretPos]);
}
else
elem.focus();
}
}
console.log( "[setCaretPosition Updated]" );
}

关于javascript - 突出显示关键字的文本区域 : strange cursor behavior,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46667222/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com