Précédent   Forum des professionnels en informatique > Webmasters - Développement Web > Contribuez
Contribuez Proposez vos articles, cours, tutoriels, questions/réponses pour les FAQ, sources et autres ressources pour la rubrique Web ainsi que ses sous-rubriques.
Partagez cette discussion sur d'autres réseaux sociaux : Viadeo Twitter Google Facebook Digg Delicious MySpace Yahoo
Réponse Proposer ce sujet en actualité
 
Outils de la discussion
Publicité
'
Vieux 04/04/2007, 20h22   #1
Expert Confirmé
 
Avatar de FremyCompany
 
Étudiant
Inscription : février 2006
Messages : 2 532
Détails du profil
Informations personnelles :
Âge : 20

Informations professionnelles :
Activité : Étudiant

Informations forums :
Inscription : février 2006
Messages : 2 532
Points : 2 903
Points : 2 903
Envoyer un message via MSN à FremyCompany
Par défaut [SRC] Document.selection pour FF !

Code :
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
    if (!document.selection && document.getSelection) {
        // SelectionObject
        function SelectionObject(Window) { 
            this.window=(Window?Window:window);
            this.document=this.window.document;
        }
        SelectionObject.prototype={
          "clear":function() {
              try {
                  var sel = this.window.getSelection();
                  sel.collapse(true);
                  sel.dettach();
              } catch (ex) {}
          },
          "createRange":function() {
              if (this.type=="none") {
                  return "no selection";
              }
              var txt = this.document.getSelection()
              var sel = {};
              try { sel=this.window.getSelection().getRangeAt(0); } catch (ex) {}
              var html = getHTMLOfSelection(this.window, this.document);
              var range = null;
 
              range = new ControlRangeObject();
              range._text=(""+txt+"");
              range._htmlText=html;
              range._range=sel;
              range.base=sel.commonAncestorContainer?sel.commonAncestorContainer:this.document.body
              range.items=new Array();
              range.addElement=range.add;
 
              try {
                  while (range.base.nodeName.substr(0,1)=="#") {
                      range.base=range.base.parentNode;
                  }
                  var index = 0; var started;
                  var current = range.base.childNodes[0];
                  while (current) {
                      if (started || current==sel.startContainer || current==sel.commonAncestorContainer) {
                          started = true;
                          range.items.push(current);
                      }
                      if (current == sel.endContainer || current==sel.commonAncestorContainer) {
                          break;
                      }
                      index++;
                      current = range.base.childNodes[index];
                  }
                  range.length=range.items.length;
              } catch (ex) {}
 
              return range;
            }
        }
 
        SelectionObject.prototype.empty=SelectionObject.prototype.clear;
        SelectionObject.prototype.createRangeControl=SelectionObject.prototype.createRange;
        SelectionObject.prototype.__defineGetter__("type", function() {
          try {
              var sel = this.window.getSelection().getRangeAt(0);
              if (sel.commonAncestorContainer.nodeName.substr(0,1)=="#") {
                  return "text";
              } else {
                  return "control";
              }
          } catch (ex) {}
          return "none";
        })
        SelectionObject.prototype.__defineSetter__("type", function() {
          // Do nothing
        })
 
        // ControlRangeObject
        function ControlRangeObject() {}
        ControlRangeObject.prototype={
            "_text":"",
            "_htmlText":"",
            "_range":null,
            "parentElement":function() {
                return this.base;
            },
            "item":function(i) {
                return this.items[i];
            },
            "add":function(node) {
                try {
                    this._range.insertNode(node);
                } catch (ex) {}
            },
            "execCommand":function(a1,a2,a3,a4) {
                var mode = document.designMode;
                document.designMode="on";
                document.execCommand(a1,a2,a3,a4);
                document.designMode=mode;
            }
        }
        // Properties
        ControlRangeObject.prototype.__defineGetter__("text",function() {
            return this._text;
        });
        ControlRangeObject.prototype.__defineSetter__("text",function(value) {
            var range = this._range;
            var p=document.createTextNode(value);
            range.deleteContents();
            range.insertNode(p)
        });
 
        ControlRangeObject.prototype.__defineGetter__("htmlText",function() {
            return this._htmlText
        });
        ControlRangeObject.prototype.__defineSetter__("htmlText",function(value) {
            var range = this._range;
            var p=document.createElement("htmlSection");
            p.innerHTML=value;
            range.deleteContents();
            range.insertNode(p)
        });
 
        document.selection=new SelectionObject();
 
        function getHTMLOfSelection (window, document) {
          var range;
          if (window.ActiveXObject && document.selection && document.selection.createRange) {
            range = document.selection.createRange();
            return range.htmlText;
          }
          else if (window.getSelection) {
            var selection = window.getSelection();
            if (selection.rangeCount > 0) {
              range = selection.getRangeAt(0);
              var clonedSelection = range.cloneContents();
              var div = document.createElement('div');
              div.appendChild(clonedSelection);
              return div.innerHTML;
            }
            else {
              return '';
            }
          }
          else {
            return '';
          }
        }
    }
Sample :
Code HTML :
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
<html><body id="body">
    <script><!--
    function getHTMLOfSelection () {
      var range;
      if (window.ActiveXObject && document.selection && document.selection.createRange) {
        range = document.selection.createRange();
        return range.htmlText;
      }
      else if (window.getSelection) {
        var selection = window.getSelection();
        if (selection.rangeCount > 0) {
          range = selection.getRangeAt(0);
          var clonedSelection = range.cloneContents();
          var div = document.createElement('div');
          div.appendChild(clonedSelection);
          return div.innerHTML;
        }
        else {
          return '';
        }
      }
      else {
        return '';
      }
    }
 
    if (!document.selection && document.getSelection) {
      function SelectionObject() {}
      SelectionObject.prototype.__defineGetter__("type", function() {
        try {
            var sel = window.getSelection().getRangeAt(0);
            if (sel.commonAncestorContainer.nodeName.substr(0,1)=="#") {
                return "text";
            } else {
                return "control";
            }
        } catch (ex) {}
        return "none";
      })
      SelectionObject.prototype.__defineSetter__("type", function() {
        // Do nothing
      })
 
      document.selection=new SelectionObject();
      document.selection.clear=function() {
        try {
            var sel = window.getSelection();
            sel.collapse(true);
            sel.dettach();
        } catch (ex) {}
      }
      document.selection.empty=document.selection.clear;
      document.selection.createRange=function() {
        if (document.selection.type=="none") {
            return "no selection";
        }
        var txt = document.getSelection()
        var sel = {};
        try { sel=window.getSelection().getRangeAt(0); } catch (ex) {}
        var html = getHTMLOfSelection();
        var range = null;
 
        var msg = typeof (sel) + "\n\n"
        for (key in sel) {
            msg+=key+"="+sel[key]+"\n\n";
        }
        document.getElementById("s4").innerHTML=msg;
 
        range = {
            "text":txt,
            "htmlText":html,
            "parentElement":function () {
                return this.base;
            },
            "base":sel.commonAncestorContainer?sel.commonAncestorContainer:document.body,
            "items":new Array(),
            "item":function(i) { return range.items[i]; },
            "add":function(node) {
                try {
                    sel.insertNode(node);
                } catch (ex) {}
            }
        }
 
        try {
            while (range.base.nodeName.substr(0,1)=="#") {
                range.base=range.base.parentNode;
            }
            var index = 0; var started;
            var current = range.base.childNodes[0];
            while (current) {
                if (started || current==sel.startContainer || current==sel.commonAncestorContainer) {
                    started = true;
                    range.items.push(current);
                }
                if (current == sel.endContainer || current==sel.commonAncestorContainer) {
                    break;
                }
                index++;
                current = range.base.childNodes[index];
            }
            range.length=range.items.length;
        } catch (ex) {}
 
        return range;
      }
    }
 
    setInterval(function() {
        try {
            var textRange = document.selection.createRange();
            var msg = (
                textRange.parentElement().nodeName+
                (textRange.parentElement().id?" id='"+textRange.parentElement().id+"'":"")+
                (textRange.parentElement().name?" name='"+textRange.parentElement().name+"'":"")+
                (textRange.parentElement().className?" class='"+textRange.parentElement().className+"'":"")+
                "\n"
            );                   
            try {
                if (document.selection.type!="text") {
                    for (var i=0; i<textRange.length; i++) {
                        msg+=(
                            "- "+
                            textRange.item(i).nodeName+
                            (textRange.item(i).id?" id='"+textRange.item(i).id+"'":"")+
                            (textRange.item(i).name?" name='"+textRange.item(i).name+"'":"")+
                            (textRange.item(i).className?" class='"+textRange.item(i).className+"'":"")+                    
                            "\n"
                        );
                    }
                }
            } catch (ex) {}
 
            document.getElementById("s4").innerHTML=""
            document.getElementById("s5").innerHTML=""
            document.getElementById("s6").innerHTML=""
            document.getElementById("s4").appendChild(document.createTextNode(msg));
            document.getElementById("s5").appendChild(document.createTextNode(textRange.htmlText));
            document.getElementById("s6").appendChild(document.createTextNode(textRange.text));
        } catch (ex) {}
    }, 1000)
    --></script>
    -Body-<br/>
    <span id="span1">
        -1-<br/>
        <span id="span2">
            -2-<br/>
            <span id="span3">
                -3-
            </span>
        </span>
    </span>
    <br/><br/>
    Selection :
    <pre id="s4">
    </pre>
    HTML Selection :
    <pre id="s5">
    </pre>
    Text Selection :
    <pre id="s6">
    </pre>
</body></html>
__________________
Fremy
Pour vos développements Web et une navigation agréable, le tout gratuit :
1) IE 8 + IE7Pro (Si vous ne connaissez pas IE7Pro, essayez !)
2) FF 3 + Web Developper Toolbar + AdBlockPlus + FireBug + GreaseMonkey
FremyCompany est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 05/04/2007, 07h53   #2
Modérateur
 
Avatar de Bisûnûrs
 
Josselin
Développeur Web
Inscription : janvier 2004
Messages : 9 050
Détails du profil
Informations personnelles :
Nom : Josselin
Âge : 29
Localisation : France, Rhône (Rhône Alpes)

Informations professionnelles :
Activité : Développeur Web

Informations forums :
Inscription : janvier 2004
Messages : 9 050
Points : 12 181
Points : 12 181
Heu, ça ne suffit pas pour FF :

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
 
   var tag = document.getElementById('truc');
   [..]
   else if(tag.selectionStart || tag.selectionStart == 0){ // Moz
      if(tag.selectionEnd > tag.value.length)
         tag.selectionEnd = tag.value.length;
 
      var firstPos = tag.selectionStart;
      var secondPos = tag.selectionEnd + text1.length;
      var contenuScrollTop = tag.scrollTop;
 
      tag.value = tag.value.slice(0,firstPos)  + text1 + tag.value.slice(firstPos);
      tag.value = tag.value.slice(0,secondPos) + text2 + tag.value.slice(secondPos);
 
      tag.selectionStart = firstPos + text1.length;
      tag.selectionEnd = secondPos;
      tag.focus();
      tag.scrollTop = contenuScrollTop;
   }
Bisûnûrs est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 05/04/2007, 09h49   #3
Expert Confirmé
 
Avatar de FremyCompany
 
Étudiant
Inscription : février 2006
Messages : 2 532
Détails du profil
Informations personnelles :
Âge : 20

Informations professionnelles :
Activité : Étudiant

Informations forums :
Inscription : février 2006
Messages : 2 532
Points : 2 903
Points : 2 903
Envoyer un message via MSN à FremyCompany
Et mais la tu ne génère pas un document.selection...

Comment tu veux faire, avec ta méthode, pour récupérer le code HTML de la sélection ? Mon code permet de copier quasiment à l'identique document.selection.

Regarde mon exemple, tu comprendras mieux l'intérêt

[EDIT]
Citation:
Format supporté :
Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/* COMMENTAIRE
 
  // Utilisation
  var textRange = document.selection.createRange()
 
  // format supporté par selection
  document.selection = {
    "type":String["none","text","control"],
    "createRange":textRange,
  }
 
  // format supporté par textRange
  textRange = {
    "text":String,
    "htmlText":String,
    "parentElement":function() as HTMLElement,
    "length":Integer,
    "item":function(index) as HTMLElement,
    "add":function(node),
    "addElement":function(node),
    "execCommand":function(...) as CommandResult
  }
 
*/
__________________
Fremy
Pour vos développements Web et une navigation agréable, le tout gratuit :
1) IE 8 + IE7Pro (Si vous ne connaissez pas IE7Pro, essayez !)
2) FF 3 + Web Developper Toolbar + AdBlockPlus + FireBug + GreaseMonkey
FremyCompany est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 05/04/2007, 10h06   #4
Modérateur
 
Avatar de Bisûnûrs
 
Josselin
Développeur Web
Inscription : janvier 2004
Messages : 9 050
Détails du profil
Informations personnelles :
Nom : Josselin
Âge : 29
Localisation : France, Rhône (Rhône Alpes)

Informations professionnelles :
Activité : Développeur Web

Informations forums :
Inscription : janvier 2004
Messages : 9 050
Points : 12 181
Points : 12 181
Ben ma méthode permettait d'insérer des tags en fonction de la sélection dans un textarea ou un input, je pensais qu'il en serait presque de même, en retouchant un peu ce code pour les autres éléments de la page. ^^

Je m'étais apparemment trompé et je viens de tester ton code qui marche à merveille.
Bisûnûrs est déconnecté   Envoyer un message privé Réponse avec citation 00
Vieux 14/02/2008, 07h21   #5
Membre confirmé
 
Avatar de renaud26
 
Inscription : mars 2003
Messages : 1 043
Détails du profil
Informations personnelles :
Âge : 48
Localisation : France, Puy de Dôme (Auvergne)

Informations forums :
Inscription : mars 2003
Messages : 1 043
Points : 285
Points : 285
Bonjour et bravo pour ce code...fallait le faire...
Comme ça dépasse, de loin, mes compétences, je me suis contenté de copier "bêtement" et de tenter d'adapter...

J'ai utilisé ce code, plutôt que celui paru sur CS. Je voudrais pouvoir ajouter des balises HTML sur des mots sélectionnés dans un textarea.

Code :
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 
<script src="document.selection.js"></script>
<script>
function insertBalise(input, name, args) {
// Donne le focus à l'élément
input.focus();
// Si rien n'est sélectionné, il faut mettre la séléction en fin de boite de texte sous FireFox
if (document.selection instanceof SelectionObject && input.selectionStart == 0 && input.selectionEnd == 0) {
input.selectionStart = input.selectionEnd = input.value.length;
}
// Méthode commune pour ajouter la balise
var range = document.selection.createRange();
range.text = "<"+name+(args?"="+args:"")+">"+range.text+"</"+name+">";
}
</script>
</head>
Puis côté textarea

Code :
1
2
3
 
<img src="images/gras.gif" onclick="insertBalise(document.getElementById('descriptif'),'b','')">
<textarea style="width: 100%" name="descriptif" id="descriptif"></textarea>
Ca fonctionne nickel sous IE. Sous FF, la balise <b>mot</b> s'affiche bien, mais pas dans le textarea, entre l'image et le champ ! Le champ n'a pas le focus. Où est ce que j'ai loupé quelque chose ?

D'avance merci et bonne journée.
renaud26 est déconnecté   Envoyer un message privé Réponse avec citation 00
Réponse Proposer ce sujet en actualité
Outils de la discussion



Fuseau horaire GMT +2. Il est actuellement 01h26.


 
 
 
 
Partenaires

Hébergement Web