Este artigo descreve o método de implementar o JS para inserir conteúdo em um local especificado em uma div. Assim como o editor que usamos, compartilhamos com você para sua referência. O método de implementação específico é o seguinte:
Primeiro, deixe o modo de edição de habilitação de divisão
Copie o código do código da seguinte
Ligue o modo de edição da div, configurando contentabable = true. Dessa forma, o div pode inserir conteúdo como a caixa de texto.
Não há mais falador. Aqui está como obter ou definir a posição do cursor.
2 etapas:
① Obtenha a posição do cursor na div
② Mudar a posição do cursor
Copie o código da seguinte forma: var cursor = 0; // Posição do cursor
Document.OnselectionChange = function () {
var range = document.selection.createrange ();
var srcele = range.parentElement (); // obtenha o elemento atual
var cópia = document.body.createTexTrange ();
Copy.MoveToElementText (SRCELE);
for (cursor = 0; copy.comPareEndPoints ("startTostart", range) <0; cursor ++) {
Copy.MoVestart ("caractere", 1); // Alterar a posição do cursor, na verdade, estamos gravando o número de cursores.
}
}
Vincular o evento de mudança do cursor ao documento. Usado para gravar a posição do cursor.
Dessa forma, você pode obter a posição do cursor da div.
Copie o código da seguinte forma: função movend (obj) {
lytxt1.focus ();
var r = document.selection.createrange ();
// Como aqui começa a se mover do cursor atual (parece que a caixa de texto começa a partir de 0.), precisamos obter a posição atual do cursor e calcular quantos bits se moverem, para que o cursor possa ser movido para a posição desejada.
R.Movestart ('personagem', lytxt1.innertext.length - cursor);
R.Collapse (True);
R.Select ();
}
Através do exposto, podemos mover o cursor na div até o fim
Um exemplo completo
Copie o código da seguinte forma: <button type = "button" onclick = "document.getElementById ('test'). Focus (); inserthtmlatcaret ('<b> inserido </b>');"> inserir caractere </button>
<div contentedable = "true" style = "altura: 50px; borda: 2px vermelho sólido;" id = "teste"> </div>
função inserthtmlatcaret (html) {
var sel, intervalo;
if (window.getSelection) {
// IE9 e não
SEL = window.getSelection ();
if (sel.getrangaat && Sel.rangeCount) {
range = Sel.Getrangaat (0);
range.DeleteContents ();
// range.createContextualfragment () seria útil aqui, mas é
// não-padrão e não suportado em todos os navegadores (ie9, por um)
var el = document.createElement ("div");
el.innerhtml = html;
var fragment = document.createCumentFragment (), nó, lastNode;
while ((node = el.firstchild)) {
lastNode = fragment.appendChild (nó);
}
range.insertNode (frag);
// preservar a seleção
if (lastNode) {
range = range.cloneRange ();
range.setSTartafter (LastNode);
range.collapse (true);
Sel.removeallLanges ();
SEL.ADDRANGE (RANGE);
}
}
} else if (document.selection && document.selection.type! = "Control") {
// ou seja, <9
Document.Selection.Createrange (). Pastehtml (html);
}
}
Outro exemplo baseado em jQuery
Copie o código da seguinte forma: <! Doctype html public "-// w3c // dtd xhtml 1.0 transitória // pt" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta content = "text/html; charset = utf-8" http-equiv = "content-type">
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"> </script>
<Title> contentável </ititle>
<estilo>
*{
margem: 0; preenchimento: 0;
}
.im-mensage-area {
largura: 98%;
preenchimento: 2px;
Altura: 75px;
Fronteira:#000 1px sólido;
Antecedentes: #FFF;
Fonte: ARIAL 12PX/20PX, "5B8B4F53";
Word-wrap: Break-Word;
transbordamento-y: automático;
altura de linha: 1;
}
.UL {Display: Nenhum;}
.UL Li {
Background-Color: #CCC;
Largura: 50px;
}
</style>
<Script Language = "JavaScript" type = "text/javascript">
função inimage (text) {
var obj = $ (".
intervalo var, nó;
if (! obj.hasfocus) {
obj.focus ();
}
if (window.getSelection && window.getSelection (). getrangeat) {
range = window.getSelection (). getrangeat (0);
range.collapse (false);
node = range.createContextualFragment (texto);
var c = node.lastChild;
range.insertNode (nó);
if (c) {
range.setEndafter (c);
range.setStartafter (c)
}
var j = window.getSelection ();
J.RemoveallLanges ();
J.AdDRANGE (RANGE);
} else if (Document.Selection && Document.Selection.Createrange) {
Document.Selection.CreaterRange (). PasteHtml (texto);
}
}
$ (document) .ready (function () {
$ ('#botão'). Clique (function () {
$ ('. Ul'). show ();
})
$ ('. ul li'). cada (function () {
$ (this) .Click (function () {
inimage ($ (this) .Text ());
})
})
});
</script>
</head>
<Body>
<div contentedable = "true" id = "im_message_area"> <br> </div>
<a href = "javascript: void (0)" id = "button"> botão </a>
<ul>
<li> (risos) </li>
<li> (Cry) </li>
<li> (安) </li>
</ul>
</body>
</html>
Espero que este artigo seja útil para a programação JavaScript de todos.