js 内容可编辑 - 防止写入新插入的元素
js contenteditable - prevent from writing into newly inserted element
我正在研究一个简单的语法高亮笔,用类替换带有 dom 元素的文本。
说,我有一个
<div contenteditable="true">
Some text. | And some other text.
</div>
光标位于 | 管道
如果用户键入foo
<div contenteditable="true">
Some text. foo| And some other text.
</div>
我替换它,然后在插入的元素之后设置选择
<div contenteditable="true">
Some text. <span class="highlight-foo">foo</span>| And some other text.
</div>
但是如果你输入,你输入跨度。不管了。
//类型栏
<div contenteditable="true">
Some text. <span class="highlight-foo">foobar|</span> And some other text.
</div>
我不想要这样,但我无法在新插入的元素之后设置选择。
<div contenteditable="true">
Some text. <span class="highlight-foo">foo</span>bar| And some other text.
</div>
这是进行突出显示和替换的JS。
...
// chunk is the variable that holds foo, if we stick the the above example..
// select it
range.setStart(range.startContainer, range.startOffset-chunk.length);
// add it to the range
sel.addRange(range);
// replace it..then set the range to the textNode after the span
// because after the injection selection.anchorNode is the textNode inside the span..
// in chrome, however, this below sets the range correctly.
range.setStart(sel.anchorNode.parentNode.nextSibling, 0);
// and it's all good until now, but adding the range to the selection does nothing..
sel.removeAllRanges();
sel.addRange(range)
// the selection is still inside the span..
如何解决这个问题? oO 我读了很多关于它的内容,甚至在这里看了很多问题,但没有关于这个特定问题的内容。
我假设你正在WebKit中测试这个。WebKit 的插入符号处理可防止您将插入符号放置在文本节点的开头:https://bugs.webkit.org/show_bug.cgi?id=23189。在 Firefox 中,您的代码应该没问题。
解决方法都很糟糕。一种是插入一个零宽度的空格(例如 'u200B
)并选择它,但随后您必须添加特殊代码来处理箭头键和代码以删除零宽度空格。
更新
另一种解决方法是使用 WebKit 对链接有一个特殊情况,它强制插入符号在链接之后:
http://jsfiddle.net/RfMju/
因此,您可以做的(令人不快但可行的)是,当您希望插入符号进入突出显示的元素内部并将其更改为链接时,可以使用<span>
。
相关文章:
- 如何jQuery-Add按钮最多插入10个新输入
- 剑道网格-插入具有外部列的新对象失败
- 在DIV中动态插入HTML并访问新元素
- CRM 2011-在插入新记录或修改现有记录时捕获子网格的事件
- 如何从地图导出图像并将其插入到新的PDF文件中
- 获取每种语言的跨度标题,并插入新的跨度中
- 将新数据项插入对象
- 当新数据插入 MySQL 时,AJAX 通知警报弹出或发出声音
- 节点发布 将新记录插入我的数据库不会返回新条目的数据
- 如何将新元素插入'这'子元素Jquery
- 在插入的节点后插入插入符号
- 为什么没有将新条目插入数据库
- 如何使用Javascript将新值插入到每个键值的数组
- 为什么不插入插入执行
- 将多个插入插入到一个表中
- 如何从angularjs中的子控制器将新行插入表中
- 使用 JS 将新代码插入页面,并带有变量
- 只在新记录插入数据库时设置ajax调用
- Ember.js:如何在新项插入到ArrayController后应用jquery插件
- 如何将新记录插入到现有集合:Sails.js