【发布时间】:2018-08-23 23:09:01
【问题描述】:
我正在尝试获取所选文本的位置,将其替换为一些 HTML,然后我想保留所选文本的位置,以便下次渲染 html 时,我想在选定的文字
我在 Div 中显示了一些内容
现在我选择文本“De finibus 的加扰部分”,它位于第 2 行并且从开始的一些偏移量开始。我将此文本替换为文本周围的跨度,例如:
function textSelection() {
var sel = window.getSelection();
var range = sel.getRangeAt(0).cloneRange();
var markerTextChar = range.extractContents();
var markerEl, markerId = "sel_" + new Date().getTime() + "_" + Math.random().toString().substr(2);
markerEl = document.createElement("span");
markerEl.id = markerId;
markerEl.appendChild(markerTextChar);
range.insertNode(markerEl);
markerEl.style.backgroundColor = ' rgba(246,195,66,0.3)';
markerEl.style.cursor = 'pointer';
}
<div id='page-view' onmouseup='textSelection()'> In publishing and graphic design, lorem ipsum is a filler text or greeking commonly used to demonstrate the textual elements of a graphic document or visual presentation. Replacing meaningful content with placeholder text allows designers to design the
form of the content before the content itself has been produced. The lorem ipsum text is typically a scrambled section of De finibus bonorum et malorum, a 1st-century BC Latin text by Cicero, with words altered, added, and removed to make it nonsensical,
improper Latin.
</div>
现在我向这个跨度添加样式以突出显示选择。现在我要做的是保存这个位置,以便下次显示 html 页面时,我想突出显示相同的选择。请注意,在其他位置可能会重复相同的选定文本,因此我不想无意中突出显示错误的位置。
- 有什么方法可以实现吗?
- 包含 Div 的文本没有“contenteditable”属性
- 到目前为止,我所拥有的是获取所选文本的“clientRects”并创建一个 div 并向该 div 添加样式并附加到正文,但我不想这样做
- 实际文本的 HTML 是在后端使用 MarkDown 等标记语言解析器生成的
编辑:
让我添加更多细节。像 github wiki 一样,我通过解析内容并根据所选语言模式(如 Markdown/Textile)生成 html 来显示 wiki 的内容。我想要一种在编辑页面时以某种方式将所选文本映射到实际文本行号的方法。单击页面编辑时,使用 codemirror 代码编辑器显示内容。
谢谢
【问题讨论】:
-
请修复我为您制作的 sn-p - 例如通过添加事件处理程序
-
@mplungjan 谢谢,刚刚更正了 sn-p
-
反对者:请解释一下..
-
@mplungjan 你对此有什么想法吗?
-
不超过你得到的。 SO 用户确实希望发布者具有一定程度的能力来接受建议并自定义代码以供自己使用,而不是免费实现您的所有规范。在任何情况下,使用差异类型工具可能会更好地处理您正在尝试做的事情
标签: javascript html markdown codemirror textselection