1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
|
function insertTag(startTag, endTag, textareaId, tagType) {
var field = document.getElementById(textareaId);
var scroll = field.scrollTop;
field.focus();
/* === Partie 1 : on récupère la sélection === */
if (window.ActiveXObject) {
var textRange = document.selection.createRange();
var currentSelection = textRange.text;
} else {
var startSelection = field.value.substring(0, field.selectionStart);
var currentSelection = field.value.substring(field.selectionStart, field.selectionEnd);
var endSelection = field.value.substring(field.selectionEnd);
}
/* === Partie 2 : on analyse le tagType === */
if (tagType) {
switch (tagType) {
case "lien":
// Si c'est un lien
endTag = "</a>";
if (currentSelection) { // Il y a une sélection
if (currentSelection.indexOf("http://") == 0 || currentSelection.indexOf("https://") == 0 || currentSelection.indexOf("ftp://") == 0 || currentSelection.indexOf("www.") == 0) {
// La sélection semble être un lien. On demande alors le libellé
var label = prompt("Quel est le libellé du lien ?") || "";
startTag = "<a href=\"" + currentSelection + "\" target='_blank'>";
currentSelection = label;
} else {
// La sélection n'est pas un lien, donc c'est le libelle. On demande alors l'URL
var URL = prompt("Quelle est l'url ?");
startTag = "<a href=\"" + URL + "\" target='_blank'>";
}
} else { // Pas de sélection, donc on demande l'URL et le libelle
var URL = prompt("Quelle est l'url ?") || "";
var label = prompt("Quel est le libellé du lien ?") || "";
startTag = "<a href=\"" + URL + "\" target='_blank'>";
currentSelection = label;
}
break;
case "citation":
// Si c'est une citation
break;
}
}
/* === Partie 3 : on insère le tout === */
if (window.ActiveXObject) {
textRange.text = startTag + currentSelection + endTag;
textRange.moveStart("character", -endTag.length - currentSelection.length);
textRange.moveEnd("character", -endTag.length);
textRange.select();
} else {
field.value = startSelection + startTag + currentSelection + endTag + endSelection;
field.focus();
field.setSelectionRange(startSelection.length + startTag.length, startSelection.length + startTag.length + currentSelection.length);
}
field.scrollTop = scroll;
} |