我正在努力实现项目,我必须用 JavaScript 做一个所见即所得的编辑器。我无法使用现有的编辑器,因为我需要使用我的插件(例如 colorPicker
或 imagePicker
)。
现在我有这个 HTML:
<div class="K_editor" id="idExample">
<div class="K_links">
<div class="K_editor_link K_editor_linkBold">B</div>
<div class="K_editor_link K_editor_linkItalic">I</div>
<div class="K_editor_link K_editor_linkUnderline">U</div>
</div>
<iframe width="696" height="212" frameborder="0" src="js/myEditor_iFrame.php">
<html>
<head/>
<body>
<div id="contentIframe" contenteditable="true">
This is a test code, with <strong>bold</strong> text and <em>italic</em> text.
</div>
</body>
</html>
</iframe>
<input type="submit"/>
</div>
在事件中点击 .K_editor_link
, 一个函数是用参数打开的:
-
tagStart
(例如<u>
或<span style="color:#AB1;">
) -
tagEnd
(例如</u>
或</span>
) -
id
(此处为idExample
)
我知道在 Textarea
上获得选集但是setSelectionRange()
, .selectionStart
和 .selectionEnd
仅适用于 textbox
(XUL), input
(XHTML) 或 textarea
(XHTML)。
我能做什么?
最佳答案
这是我使用的代码。自从几个月前我在 SO 上找到它以来,我不能相信它。不记得在哪里。希望它对你有用。
function getSelectionHtml()
{
var html = "";
if (typeof window.getSelection != "undefined")
{
var sel = window.getSelection();
if (sel.rangeCount)
{
var container = document.createElement("div");
for (var i = 0, len = sel.rangeCount; i < len; ++i) {
container.appendChild(sel.getRangeAt(i).cloneContents());
}
html = container.innerHTML;
}
} else if (typeof document.selection != "undefined") {
if (document.selection.type == "Text") {
html = document.selection.createRange().htmlText;
}
}
return html;
}
代码来自这个问题:window.getSelection return html
关于javascript - DIV 内容上的 getSelectionEditable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2713270/