Comment puis-je mettre en retrait chaque ligne du texte sélectionné dans un contrôle de zone de texte à l'aide de JavaScript. Quelque chose de similaire à l'Exemple de code bouton de l'éditeur Stack Overflow.Retrait du texte sélectionné avec JavaScript
MISE À JOUR: Affichage du code de Et, j'ai écrit une solution, mais ne fonctionne qu'avec Firefox (également).
Les fonctions est:
function indentSelection() {
var selection, newValue;
var txt = document.getElementById("txt");
var start = txt.selectionStart;
var end = txt.selectionEnd;
// extend the selecction start until the previous line feed
start = txt.value.lastIndexOf("\n", start);
// if there isn't a line feed before,
// then extend the selection until the begging of the text
if (start == -1) {
start = 0;
}
// if the selection ends with a line feed,
// remove it from the selection
if (txt.value.charAt(end - 1) == "\n") {
end = end - 1;
}
// extend the selection end until the next line feed
end = txt.value.indexOf("\n", end);
// if there isn't a line feed after,
// then extend the selection end until the end of the text
if (end == -1) {
end = txt.value.length;
}
// move the selection to a new variable
selection = txt.value.substring(start, end);
// add four spaces before line feeds
selection = selection.replace(/^(?=.+)/mg, " ");
// rebuild the textarea content
newValue = txt.value.substring(0, start);
newValue += selection;
newValue += txt.value.substring(end);
txt.value = newValue;
}
Un exemple pourrait être:
<textarea id="txt" cols="80" rows="8">bla bla bla
bla bla bla
bla bla bla
bla bla bla</textarea>
<a href="#" onclick="indentSelection();return false;">indent selection!</a>
Vous trouverez ci-dessous une solution qui prend également en charge IE6 .. :) –