我正在从头开始创建一个文本编辑器。
加粗代码
$('#bold').click(function(){
var start = window.getSelection().toString();
var bolded = '<b>' + start + '</b>';
var cursorPositionBegin = $('#TextEditor').prop("selectionStart");
var cursorPositionEnd = $('#TextEditor').prop("selectionEnd");
// to check
alert(bolded);
})
HTML 代码
<table width="50%">
<tr>
<td>
<div>
<div>
<span><input type=button value="B" id="bold"></span>
</div>
<div contenteditable="true">
<textarea cols="47" rows="23" placeholder="editor" id="TextEditor"></textarea>
</div>
</div>
</td>
</tr>
</table>
当我针对选定的字符集单击#bold 时,我想在#TextEditor 中添加字符。我想也许获取光标的开始和结束位置可以帮助将开始和结束与字符一起分解和连接在一起以形成我需要的内容。
我也使用 jQuery
[更新1]
或者有其他方法可以完成我的要求吗?
[更新2]
将 contenteditable="true"
添加到 #TextEditor id 放置的 div
我们将不胜感激您的帮助。
最佳答案
正如 @weBBer 所说,您将不允许在 textarea 元素内添加标签,请使用带有属性 contenteditable="true"的 div
$('#bold').click(function(){
var string = window.getSelection().toString();
var bolded = '<b>' + string + '</b>';
var selC, range;
if (window.getSelection) {
selC = window.getSelection();
if (selC.rangeCount) {
range = selC.getRangeAt(0);
range.deleteContents();
range.insertNode(document.createTextNode(bolded));
}
} else if (document.selection && document.selection.createRange) {
range = document.selection.createRange();
range.text = bolded;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="50%">
<tr>
<td>
<div>
<div>
<span><input type=button value="B" id="bold"></span>
</div>
<div contenteditable="true" style="height: 300px;width: 300px;border: 1px solid black">
</div>
</div>
</td>
</tr>
</table>
关于javascript - 获取SelectionStart之前和SelectionEnd之后的所有文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51797420/