我正在尝试编写一个简单的网络文本编辑器。 我想要做的是让用户在文本区域(或类似文本区域的输入)上键入内容,然后使用鼠标或使用 Shift 键选择文本,然后单击按钮以应用基于颜色的效果。 我的问题是这样的:
- 如何以一种不会丢失的方式捕获选择 按钮被点击
- 如何保存文本和选择
- 如何做到所见即所得
附:我不需要完整的富文本编辑器。我只需要一种效果
谢谢
最佳答案
how do I capture the selection in a way it's not lost when the button is clicked
how to save the text and the selection
我将此完全归功于@TimDown's answer to a different question here 。它将当前选择替换为另一个字符串。
我们通过获取颜色选择器的值并将其放入 span 标记中并插入当前选定的文本来创建字符串。
- how to make it WYSIWYG
使用 contenteditable
div 并在表单提交时将输出汇集到隐藏的文本区域。
这里一切都在一起了。再说一遍,第一个函数 replaceSelection()
不是我的代码。
document.getElementById('color').onchange = function() {
var replace = document.createElement('span');
replace.style.color = this.value;
replace.textContent = window.getSelection().toString();
replaceSelection(replace.outerHTML, true);
}
document.getElementById('wysiwyg').onsubmit = function() {
document.getElementById('result').textContent = document.getElementById('#input').innerHTML;
}
// @TimDown
function replaceSelection(html, selectInserted) {
var sel, range, fragment;
sel = window.getSelection();
// Test that the Selection object contains at least one Range
if (sel.getRangeAt && sel.rangeCount) {
// Get the first Range (only Firefox supports more than one)
range = window.getSelection().getRangeAt(0);
range.deleteContents();
// Create a DocumentFragment to insert and populate it with HTML
// Need to test for the existence of range.createContextualFragment
// because it's non-standard and IE 9 does not support it
if (range.createContextualFragment) {
fragment = range.createContextualFragment(html);
} else {
// In IE 9 we need to use innerHTML of a temporary element
var div = document.createElement("div"), child;
div.innerHTML = html;
fragment = document.createDocumentFragment();
while ( (child = div.firstChild) ) {
fragment.appendChild(child);
}
}
var firstInsertedNode = fragment.firstChild;
var lastInsertedNode = fragment.lastChild;
range.insertNode(fragment);
if (selectInserted) {
if (firstInsertedNode) {
range.setStartBefore(firstInsertedNode);
range.setEndAfter(lastInsertedNode);
}
sel.removeAllRanges();
sel.addRange(range);
}
}
}
#input {
min-height: 100px;
border-radius: 5px;
border: 1px solid #ccc;
padding: 5px;
margin-bottom: 1px;
}
#result {
display: none;
}
#wysiwyg input[type="submit"] {
height: 2em;
float: right;
}
<form action="" method="post" id="wysiwyg">
<div id="input" contenteditable="true"></div>
<textarea name="result" id="result"></textarea>
<input type="color" id="color" />
<input type="submit" value="submit" />
</form>
关于javascript 文本编辑器 - 如何捕获选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30584054/