jquery附加到索引位置

jquery appending to a index location

本文关键字:索引 位置 jquery      更新时间:2023-09-26

我正在尝试制作一个rtf风格的文本框。当我提醒选择时,我的get选择有效。我正试图让它在选择之前和之后附加一个。但我所尝试的一切都只是不断地附加到html的末尾。

我的Html是非常简单的

<p id="textblock" contenteditable="true">
This is just a simple paragraph tag that is content editable. the plan is to make it responsive to RTF controls like bold, italics, and other options.     
</p>
<button id="boldButton">BOLD</button>
<button id="viewButton">ViewHtml</button>
<button id="selection">ViewSelection</button>

我的jquery是

$( "#boldButton" ).click(function() {
    Boldify();
});
$( "#viewButton" ).click(function() {
  alert( $("#textblock").html() );
});
$( "#selection" ).click(function() {
  alert( document.getSelection().toString());
});
function Boldify(){
    var startIndex = document.getSelection().getRangeAt(0).startOffset;
    var endIndex = document.getSelection().getRangeAt(0).endOffset;
$("<strong>").appendTo("#textblock").index(window.getSelection());
$("</strong>").appendTo("#textblock").index(endIndex);
}

这是我的小提琴。http://jsfiddle.net/3oaup7gn/我觉得我很亲近。但我好像错过了什么。我尝试过使用静态索引和getSelection()索引,但它总是做同样的事情。

我的朋友,你必须使用execCommand(),只需将其添加到Boldify()函数中即可。

document.execCommand('bold', false, true);

阅读整个API:https://developer.mozilla.org/en-US/docs/Web/API/document.execCommand