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

JavaScript Discussion :

Barre de recherche


Sujet :

JavaScript

  1. #1
    Membre du Club
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    83
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 83
    Points : 51
    Points
    51
    Par défaut Barre de recherche
    Bonjour,
    En haut d'une page html, je souhaiterais intégrer une barre de recherche.
    Si l'utilisateur entre un mot présent dans la page, la vue scroll vers ce mot et est surligné.

    J'ai trouvé sur le net des scripts, mais bizarrement, je n'arrive pas à les utiliser.

    Le dernier que j'ai testé :
    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
    <html>
    <head>
    <script>
    var TRange=null;
     
    function findString (str) {
     if (parseInt(navigator.appVersion)<4) return;
     var strFound;
     if (window.find) {
     
      // CODE FOR BROWSERS THAT SUPPORT window.find
     
      strFound=self.find(str);
      if (!strFound) {
       strFound=self.find(str,0,1);
       while (self.find(str,0,1)) continue;
      }
     }
     else if (navigator.appName.indexOf("Microsoft")!=-1) {
     
      // EXPLORER-SPECIFIC CODE
     
      if (TRange!=null) {
       TRange.collapse(false);
       strFound=TRange.findText(str);
       if (strFound) TRange.select();
      }
      if (TRange==null || strFound==0) {
       TRange=self.document.body.createTextRange();
       strFound=TRange.findText(str);
       if (strFound) TRange.select();
      }
     }
     else if (navigator.appName=="Opera") {
      alert ("Opera browsers not supported, sorry...")
      return;
     }
     if (!strFound) alert ("String '"+str+"' not found!")
     return;
    }
    </script>
    </head>
     
    <body>
     <form method="get" action="">
    	<input type="text" name="search" id="search" value="" />
    	<input type="submit" name="submit" value="Search" />
    </form>
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    Section 1.10.32 du "De Finibus Bonorum et Malorum" de Ciceron (45 av. J.-C.)
     
    "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
    Traduction de H. Rackham (1914)
     
    "But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"
    Section 1.10.33 du "De Finibus Bonorum et Malorum" de Ciceron (45 av. J.-C.)
     
    "At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat."
    Traduction de H. Rackham (1914)
     
    "On the other hand, we denounce with righteous indignation and dislike men who are so beguiled and demoralized by the charms of pleasure of the moment, so blinded by desire, that they cannot foresee the pain and trouble that are bound to ensue; and equal blame belongs to those who fail in their duty through weakness of will, which is the same as saying through shrinking from toil and pain. These cases are perfectly simple and easy to distinguish. In a free hour, when our power of choice is untrammelled and when nothing prevents our being able to do what we like best, every pleasure is to be welcomed and every pain avoided. But in certain circumstances and owing to the claims of duty or the obligations of business it will frequently occur that pleasures have to be repudiated and annoyances accepted. The wise man therefore always holds in these matters to this principle of selection: he rejects pleasures to secure other greater pleasures, or else he endures pains to avoid worse pains."
    </body>
    </html>
    Venant de ce site : http://www.javascripter.net/faq/searchin.htm


    Merci par avance si l'un de vous a une solution.

  2. #2
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    16 959
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 16 959
    Points : 44 122
    Points
    44 122
    Par défaut
    Bonjour,
    tu appliques mal le script qui de plus date un peu.

    Regarde plutôt du coté de celui ci
    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
    <head>
        <script type="text/javascript">
            function FindNext () {
                var str = document.getElementById ("findField").value;
                if (str == "") {
                    alert ("Please enter some text to search!");
                    return;
                }
     
                var supported = false;
                var found = false;
                if (window.find) {        // Firefox, Google Chrome, Safari
                    supported = true;
                        // if some content is selected, the start position of the search 
                        // will be the end position of the selection
                    found = window.find (str);
                }
                else {
                    if (document.selection && document.selection.createRange) { // Internet Explorer, Opera before version 10.5
                        var textRange = document.selection.createRange ();
                        if (textRange.findText) {   // Internet Explorer
                            supported = true;
                                // if some content is selected, the start position of the search 
                                // will be the position after the start position of the selection
                            if (textRange.text.length > 0) {
                                textRange.collapse (true);
                                textRange.move ("character", 1);
                            }
     
                            found = textRange.findText (str);
                            if (found) {
                                textRange.select ();
                            }
                        }
                    }
                }
     
                if (supported) {
                    if (!found) {
                        alert ("The following text was not found:\n" + str);
                    }
                }
                else {
                    alert ("Your browser does not support this example!");
                }
            }
        </script>
    </head>
    <body>
        <div>LaLa, Lala, laLa , lala, lalala, tralala, some other text</div>
        <br />
        <input type="text" id="findField" value="lala" size="20" />
        <button onclick="FindNext ();">Find!</button>
    </body>
    issu de find method (window) Example HTML code 2 sur help.dottoro.com

  3. #3
    Membre du Club
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    83
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 83
    Points : 51
    Points
    51
    Par défaut
    Bonjour NoSmoking, merci pour ton message.

    En effet ce script fonctionne, par contre, je souhaite placer la barre de recherche en haut de la page.

    Quand j'inverse les positions (recherche en haut et texte après), à la recherche j'ai le texte de la barre qui est sélectionné (donc trouvé), mais pas le texte dans la page.

    Le script est annoté :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
                                // if some content is selected, the start position of the search 
                                // will be the position after the start position of the selection
    Ce qui fonctionne en effet, si je sélectionne un texte après la barre, je trouve bien le texte. Il doit y avoir un "curseur" à placer pour débuter la recherche, mais je ne trouve pas où.

  4. #4
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    16 959
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 16 959
    Points : 44 122
    Points
    44 122
    Par défaut
    Pas regardé plus avant cette méthode...mais voilà surement le pourquoi de l'IFRAME dans le code cité à ton 1st post.

    • Tu peux utiliser la même méthode mettre tes éléments de recherche dans une IFRAME
    • Tu peux ruser en CSS pour placer tes éléments de recherche en haut de la page alors qu'il apparaissent dans ton code en bas.

  5. #5
    Membre du Club
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    83
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 83
    Points : 51
    Points
    51
    Par défaut
    J'ai essayé de placer ton code dans une Iframe, mais du coup il ne semble pas chercher en dehors de ce qui est dans l'iframe. (je me suis peu être embrouillé dans les parents.)

    Comment tu ferais pour "ruser" avec le css ?

  6. #6
    Modérateur

    Avatar de NoSmoking
    Homme Profil pro
    Inscrit en
    Janvier 2011
    Messages
    16 959
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Isère (Rhône Alpes)

    Informations forums :
    Inscription : Janvier 2011
    Messages : 16 959
    Points : 44 122
    Points
    44 122
    Par défaut
    • CSS : sur base de la structure suivante
    Code html : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    <body>
    <div id="page">
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla fringilla tempus maximus. Nullam consectetur diam leo, fermentum fringilla nunc bibendum non. Maecenas faucibus felis eu tellus rhoncus faucibus. Ut ante lacus, tincidunt eget sagittis in, vestibulum at ante. Vivamus iaculis ac sem at iaculis. Vestibulum est magna, egestas congue enim vitae, rutrum convallis quam. Etiam in ex lectus. Integer mattis suscipit faucibus. Vivamus faucibus rutrum maximus. Donec ut ante enim. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos.
    </p>
    </div>
    <div id="search">
        <input type="text" id="findField" value="est" size="20">
        <button onclick="FindNext();">Find!</button>
    </div>
    </body>
    et en ajoutant le CSS suivant
    Code css : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    body{
      padding-top:2em;  /* hauteur du bandeau de recherche */
    }
    #search {
      position:absolute;
      top:.5em;
      left:.5em;
      height:2em;
    }
    • JS : application stricte de la recommandation de ton exemple initiale
    Une page contenue dans l'IFRAME comme si dessous
    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
    <html>
    <head>
    <style>
    body  {
      margin:0px;
    }
    </style>
    </head>
    <body>
    <form id="f1" name="f1" action="javascript:void()" onSubmit="if(this.t1.value!=null && this.t1.value!='') parent.findString(this.t1.value);return false;">
      <input type="text" id="t1" name="t1" value="text" size=20>
      <input type="submit" name=b1 value="Find">
    </form>
    </body>
    </html>
    tu noteras que la fonction findString est appelée en référençant parent qui est donc la fenêtre mère.

    Et dans la page mère mise en place du script de la fonction et de l'IFRAME.

  7. #7
    Membre du Club
    Profil pro
    Inscrit en
    Janvier 2007
    Messages
    83
    Détails du profil
    Informations personnelles :
    Localisation : France

    Informations forums :
    Inscription : Janvier 2007
    Messages : 83
    Points : 51
    Points
    51
    Par défaut
    Génial, ça marche !!!

    J'ai utilisé le css.

    Merci beaucoup.

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. problème de langue barre de recherche google
    Par tiliut dans le forum Firefox
    Réponses: 2
    Dernier message: 21/02/2009, 11h09
  2. Barre de recherche - Genre Firefox-Google
    Par MikeV dans le forum Général JavaScript
    Réponses: 2
    Dernier message: 18/04/2008, 13h58
  3. Une barre de recherche Qt pour Firefox
    Par Alp dans le forum Qt
    Réponses: 3
    Dernier message: 07/02/2008, 18h37
  4. Barre de recherche IE7 pour Developpez.com ?
    Par vodevil dans le forum Evolutions du club
    Réponses: 7
    Dernier message: 11/02/2007, 20h03
  5. barre de recherche dans les fonctions php pour firefox
    Par titoumimi dans le forum EDI, CMS, Outils, Scripts et API
    Réponses: 8
    Dernier message: 03/02/2006, 10h16

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