IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Contribuez Discussion :

[SRC] Document.selection pour FF !


Sujet :

Contribuez

  1. #1
    Membre expert
    Avatar de FremyCompany
    Profil pro
    Étudiant
    Inscrit en
    Février 2006
    Messages
    2 532
    Détails du profil
    Informations personnelles :
    Âge : 32
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Février 2006
    Messages : 2 532
    Points : 3 289
    Points
    3 289
    Par défaut [SRC] Document.selection pour FF !
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    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

  2. #2
    Modérateur
    Avatar de Bisûnûrs
    Profil pro
    Développeur Web
    Inscrit en
    Janvier 2004
    Messages
    9 868
    Détails du profil
    Informations personnelles :
    Âge : 40
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Janvier 2004
    Messages : 9 868
    Points : 16 258
    Points
    16 258
    Par défaut
    Heu, ça ne suffit pas pour FF :

    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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;
       }

  3. #3
    Membre expert
    Avatar de FremyCompany
    Profil pro
    Étudiant
    Inscrit en
    Février 2006
    Messages
    2 532
    Détails du profil
    Informations personnelles :
    Âge : 32
    Localisation : Belgique

    Informations professionnelles :
    Activité : Étudiant

    Informations forums :
    Inscription : Février 2006
    Messages : 2 532
    Points : 3 289
    Points
    3 289
    Par défaut
    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]
    Format supporté :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    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

  4. #4
    Modérateur
    Avatar de Bisûnûrs
    Profil pro
    Développeur Web
    Inscrit en
    Janvier 2004
    Messages
    9 868
    Détails du profil
    Informations personnelles :
    Âge : 40
    Localisation : France, Rhône (Rhône Alpes)

    Informations professionnelles :
    Activité : Développeur Web

    Informations forums :
    Inscription : Janvier 2004
    Messages : 9 868
    Points : 16 258
    Points
    16 258
    Par défaut
    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.

  5. #5
    Membre averti Avatar de renaud26
    Homme Profil pro
    Webmaster
    Inscrit en
    Mars 2003
    Messages
    1 365
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Âge : 60
    Localisation : France, Côtes d'Armor (Bretagne)

    Informations professionnelles :
    Activité : Webmaster

    Informations forums :
    Inscription : Mars 2003
    Messages : 1 365
    Points : 436
    Points
    436
    Par défaut
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    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 : Sélectionner tout - Visualiser dans une fenêtre à part
    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.

Discussions similaires

  1. select pour obtenir la taille de remplissage d'une bdd
    Par sqlakf76 dans le forum MS SQL Server
    Réponses: 9
    Dernier message: 15/07/2005, 13h44
  2. [SRC] Cherche piste pour TLabel orientable
    Par Kaejar dans le forum C++Builder
    Réponses: 16
    Dernier message: 08/06/2005, 17h13
  3. [VB.NET] [SQL] Retour d'un SELECT pour un IF/ELSE
    Par nys_00 dans le forum Windows Forms
    Réponses: 7
    Dernier message: 17/03/2005, 12h50
  4. un Select pour declencher une boucle
    Par vijeo dans le forum MS SQL Server
    Réponses: 6
    Dernier message: 17/12/2004, 15h14
  5. Requete select pour récupérer les no match entre 2 tables
    Par Celina dans le forum MS SQL Server
    Réponses: 4
    Dernier message: 16/12/2003, 11h59

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo