简体   繁体   English

在DOM元素之后移动选择

[英]Move selection after a DOM element

I'm currently building a Markdown editor for the web. 我目前正在为网络构建Markdown编辑器。 Markdown tags are previewed in realtime by appending their HTML equivalents via the Range interface. 通过Range接口附加HTML等效项,实时预览Markdown标记。 Following code is used, which should be working according to MDN: 使用以下代码,该代码应根据MDN工作:

var range = document.createRange()
var selection = window.getSelection()

range.setStart(textNode, start)
range.setEnd(textNode, end + 2)

surroundingElement = document.createElement('strong')
range.surroundContents(surroundingElement)

var cursorRange = document.createRange()
cursorRange.setStartAfter(surroundingElement)

selection.removeAllRanges()
selection.addRange(cursorRange)

Firefox works: Some bold text Firefox的工作原理:一些粗体文字

在此输入图像描述

Chrome not: Some bold text Chrome不是:一些粗体文字

在此输入图像描述

Any suggestions what could be wrong? 有什么建议可能是错的吗? Information on this subject are rare. 有关此主题的信息很少见。


Answer 回答

Thanks to @Tim Down, I fixed it using the invisible character workaround he describes in one of the links mentioned in is answer. 感谢@Tim Down,我使用他在回答中提到的一个链接中描述的隐形字符解决方法修复了它。 This is the code I'm using now: 这是我现在使用的代码:

var range = document.createRange()

range.setStart(textNode, start)
range.setEnd(textNode, end + 2)

surroundingElement = document.createElement('strong')
range.surroundContents(surroundingElement)

var selection = window.getSelection()
var cursorRange = document.createRange()

var emptyElement = document.createTextNode('\u200B')
element[0].appendChild(emptyElement)

cursorRange.setStartAfter(emptyElement)

selection.removeAllRanges()
selection.addRange(cursorRange) 

The problem is that WebKit has fixed ideas about where the caret (or a selection boundary) can go and is selecting an amended version of your range when you call the selection's addRange() method. 问题在于,当您调用选择的addRange()方法时,WebKit已经确定了插入符号(或选择边界)的位置,并且正在选择范围的修正版本。 I've written about this a few times on Stack Overflow; 我已经在Stack Overflow上写了几次这个; here are a couple of examples: 这里有几个例子:

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

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