Move selection after a DOM element
I'm currently building a Markdown editor for the web. Markdown tags are previewed in realtime by appending their HTML equivalents via the Range interface. Following code is used, which should be working according to 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
http://f.cl.ly/items/093R343i23402K190k1t/firefox.gif
Chrome not: Some bold text
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. 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. I've written about this a few times on Stack Overflow; here are a couple of examples:
上一篇: [程序名称] .exe已停止工作
下一篇: 在DOM元素之后移动选区