[英]Using javascript to select text and the containing element using createRange
I'm rolling my own generic wysiwyg editor but Im stuck selecting some text. 我正在滚动自己的通用所见即所得编辑器,但我坚持选择一些文本。 I'm using a div with contenteditable set to true to enter the text into.
我正在使用将contenteditable设置为true的div输入文本。 The problem is I'm using a
<var>
tag to highlight some text that the user is supposed to delete and rewrite in their own words. 问题是我正在使用
<var>
标记突出显示一些用户应该以自己的文字删除并重写的文本。 When the text inside the <var>
tag is clicked it highlights it as I expect but when you hit backspace it only deletes the text and not the tags ( <var>
). 单击
<var>
标记内的文本时,它会按我的预期突出显示,但是当您按退格键时,只会删除文本,而不是标记( <var>
)。 How can I tell the selection to grab a few more characters on each end of the selection so it also deletes the <var>
tags? 我怎样才能告诉选择项在选择项的每一端再抓几个字符,以便它也删除
<var>
标记? I'm using the following to make the selection happen. 我正在使用以下内容进行选择。
var range = document.createRange();
range.selectNodeContents(elem);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
Placed function on the div
's click
event. 将函数放在
div
的click
事件上。
Selected the <var>
tag. 选择
<var>
标签。
Used .selectNode
rather than .selectNodeContents
. 使用
.selectNode
而不是.selectNodeContents
。
Browsers handle it differently though. 浏览器对它的处理方式不同。 Some will add
<i></i>
tags when you enter more text, others don't, but this does remove the <var>
tag completely.... 当您输入更多文本时,有些会添加
<i></i>
标记,有些则不会,但是会完全删除<var>
标记。...
var myDiv = document.getElementById("myDiv"); var elem = document.getElementById("myVar"); myDiv.addEventListener("click", function() { var range = document.createRange(); range.selectNode(elem); var selection = window.getSelection(); selection.removeAllRanges(); selection.addRange(range); });
<div contenteditable="true" id="myDiv"> Hello, this<var id="myVar"> is a test</var> of the editor </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.