Per realizzare delle Tabstrip davvero accattivanti esiste una tecnica particolarmente indicata che consente di mediare tra difficoltà grafiche e codice Javascript. Vediamo prima di tutto come costruire un templete in Photoshop per le nostre Tabstrip:

Costruita un tabstrip simile a quella mostrata qui sopra in figura, usiamo il tool per la selezione delle area di taglio per generare la forma che avrà la nostra tabella HTML. L’uso della tabella, in questo caso, è particolarmente indicato – come vedremo, in quanto semplifica sia il design che il codice Javascript. Ritagliamo dunque la nostra Tabstrip nel modo seguente:
Nel nostro file Photoshop dobbiamo considerare tutte le combinazioni delle schede (tab). Abbiamo quindi la scheda iniziale selezionata (taglio 3), i punti intermedi (taglio 5 e taglio 7) e la scheda finale non selezionata (taglio 9) con – eventuale – bordo di rifinitura (taglio 10 – opzionale a seconda del design). Bastano poi 3 combinazioni per risolvere tutti i casi visivi. Come mostrato qui sotto:
Graficamente parlando potete disporre le schede anche in sovrapposizione e sfalsate, come mostrato qui sotto:
Questione di gusto e di necessità… tornando all’immagine completa, con le tre strisce Tabstrip per le combinazioni, le ultime due servono per risolvere i casi limite; tagliatele come mostrato qui sotto:

Il taglio 17 e il taglio 23 risolvono i due casi limite: prima tab non selezionata, ultima selezionata. Il taglio 19 è l’opposto del taglio 5 e del taglio 7, visti in precedenza. L’immagine completa che otteniamo e che possiamo salvare per futuri cambiamenti di design è la seguente:

Per non confonderci quando affronteremo la parte Javascript, il nome dei tagli è il seguente:
- taglio 3 = tabLeftFirstOn
- taglio 4 = tabStripeOn
- taglio 5 = tabMiddleOnOff
- taglio 6 = tabStripeOff
- taglio 7 = tabMiddleOffOff
- taglio 9 = tabRightLastOff
- taglio 10 = topBg
- taglio 17 = tabLeftFirstOff
- taglio 19 = tabMiddleOffOn
- taglio 23 = tabRightLastOn
Per realizzare tutto ciò ci serve adesso un codice HTML, un codice CSS e un codice Javascript come gestore dei click sulle schede tab. Il codice HTML è banale ma articolato. Quindi propongo una classe PHP in grado di generarlo ogni volta che ci serve. In sostanza si tratta di creare una tabella HTML racchiusa in determinati DIV con ID particolari che ci serviranno poi per l’esecuzione del codice Javascript e per racchiudere il design tramite i CSS. Il codice HTML generato – tanto per farsi un’idea – di un Tabstrip con quattro schede è il seguente:
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 | <div id="cscoTabStrip"> <div id="jscoTabStrip_info"> <table width="100%" cellspacing="0" cellpadding="0" border="0"> <tr> <td><div class="tabLeftFirstOn"></div></td> <td nowrap="" class="tabStripeOn"><a id="jscoTS_tab1" onclick="_onTabStrip( this );" class="tabsLink" title="Caratteristiche">Caratteristiche</a></td> <td><div class="tabMiddleOnOff"></div></td> <td nowrap="" class="tabStripeOff"><a id="jscoTS_tab2" onclick="_onTabStrip( this );" class="tabsLink" title="Come funziona">Come funziona</a></td> <td><div class="tabMiddleOffOff"></div></td> <td nowrap="" class="tabStripeOff"><a id="jscoTS_tab3" onclick="_onTabStrip( this );" class="tabsLink" title="Interfaccia">Interfaccia</a></td> <td><div class="tabMiddleOffOff"></div></td> <td nowrap="" class="tabStripeOff"><a id="jscoTS_tab4" onclick="_onTabStrip( this );" class="tabsLink" title="Richiesta Iscrizione">Richiesta Iscrizione</a></td> <td><div class="tabRightLastOff"></div></td> <td width="100%" class="topBG"></td> </tr> </table> </div> <div id="jscoTSC_jscoTS_tab1" class="tabStripContent"> <p>contenuto SCHEDA TAB 1</p> </div> <div id="jscoTSC_jscoTS_tab2" class="tabStripContentHidden"> <p>contenuto SCHEDA TAB 2</p> </div> <div id="jscoTSC_jscoTS_tab3" class="tabStripContentHidden"> <p>contenuto SCHEDA TAB 3</p> </div> <div id="jscoTSC_jscoTS_tab4" class="tabStripContentHidden"> <p>contenuto SCHEDA TAB 4</p> </div> </div> |
Il codice PHP che genera questo HTML è il seguente:
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 | // *********************************************************** // // file : tabstrip.php // Author : Giovambattista Fazioli (www.undolog.com) // Web : http://www.undolog.com // E-mail : info (at) undolog (dot) (com) // Created : 03/10/2005 10.07 // Modified : 06/11/2005 07.17 // // PROPERTIES // name - (STRING) - Nome (ID) della Window // style - (STRING) - Stile aggiuntivi in linea // tabs - (ARRAY) - Elenco delle schede (tab) // // METHODS // addTab() - Aggiunge una scheda al TabStrip // toString() - Restituisce l'output HTML per la Window // show() - Visualizza l'output HTML per la Window // // NOTE // // EXAMPLES // // *********************************************************** class CSCO_UI_TABSTRIP { // #public properties var $name; var $style; var $tabs; var $jsListener; // #private properties var $strHeader; var $strBody; // ===================================================== // CONSTRUCTOR: // ===================================================== function CSCO_UI_TABSTRIP ( $name, $jsListener="" ) { $this->name = $name; $this->jsListener = $jsListener; $this->tabs = array(); } // ===================================================== // METHOD: addTab() // // DESCRIPTION // Aggiunge una scheda al TabStrip. // // EXAMPLES // // ===================================================== function addTab( $name, $label, $tooltip, $content, $selected=false ) { $tab = array( "name" => $name, "label" => $label, "tooltip" => $tooltip, "content" => $content, "selected" => $selected ); $this->tabs[] = $tab; } // ===================================================== // METHOD: toString() // // DESCRIPTION // Restituisce l'output HTML per la TabStrip. // // EXAMPLES // // ===================================================== function toString() { // $this->strHeader = '<div id="cscoTabStrip" '. ( ($this->style != "")?'style="'.$this->style.'"':'' ).'>'. '<div '. 'id="jscoTabStrip_'.$this->name.'">'. '<table style="border-collapse: collapse;" width="100%" border="0" cellspacing="0" cellpadding="0">'. '<tr>'; $strBody = ""; // FirstLeft $classLeft = ( $this->tabs[0]["selected"] )?"tabLeftFirstOn":"tabLeftFirstOff"; $this->strHeader .= '<td><div class="'.$classLeft.'"></div></td>'; for($i=0; $i < sizeof($this->tabs); $i++) { // $classBck = ( $this->tabs[$i]["selected"] )?"tabStripeOn":"tabStripeOff"; // if( $i == ( sizeof($this->tabs) -1) ) { $classMiddle = ( $this->tabs[$i]["selected"] )?"tabRightLastOn":"tabRightLastOff"; } else { if( $this->tabs[$i]["selected"] ) { $classMiddle = "tabMiddleOnOff"; } else { $classMiddle = ( $this->tabs[$i+1]["selected"] )?"tabMiddleOffOn":"tabMiddleOffOff"; } } // // $this->strHeader .= '<td nowrap="nowrap" class="'.$classBck.'">'. '<a title="'.$this->tabs[$i]["tooltip"].'" class="tabsLink" onclick="_onTabStrip( this '.( ($this->jsListener!="")?(",'".$this->jsListener."'"):"" ).' );" id="jscoTS_'.$this->tabs[$i]["name"].'">'.$this->tabs[$i]["label"].'</a>'. '</td>'. '<td><div class="'.$classMiddle.'"></div></td>'; // $class = ($this->tabs[$i]["selected"])?"tabStripContent":"tabStripContentHidden"; $strBody .= '<div class="'.$class.'" id="jscoTSC_jscoTS_'.$this->tabs[$i]["name"].'">'.$this->tabs[$i]["content"].'</div>'; // } // align foo $this->strHeader .= '<td class="topBG" width="100%"></td>'. '</tr></table>'; $this->strBody = '<div>'.$strBody.'</div>'; // return( $this->strHeader.$this->strBody.'</div></div>'); } // ===================================================== // METHOD: show() // // DESCRIPTION // Visualizza l'output HTML per la TabStrip. // // EXAMPLES // // ===================================================== function show() { echo ( $this->toString() ); } } // END OF SCO_UI_TABSTRIP.PHP FILE |
Per usare la classe basta questo frammento:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // File con la definizione della class require "tabstrip.php"; // Creo oggetto Tabstrip $t = new CSCO_UI_TABSTRIP( "info" ); // Creo / leggo da file - i contenuti delle schede $s1 = "Contenuto 1"; $s2 = "Contenuto 2"; $s3 = "Contenuto 3"; $s4 = "Contenuto 4"; // Aggiungo schede $t->addTab("tab1","Caratteristiche","Caratteristiche", $s1, true); $t->addTab("tab2","Come funziona","Come funziona", $s2); $t->addTab("tab3","Interfaccia","Interfaccia", $s3); $t->addTab("tab4","Richiesta Iscrizione","Richiesta Iscrizione", $s4); // Mostro tutto - in alternativa usare toString() method $t->show(); |
Definiamo ora gli stili:
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 | div#cscoTabStrip {font-size:13px} div#cscoTabStrip .tabStripeOff a.tabsLink, div#cscoTabStrip .tabStripeOff a.tabsLink:link, div#cscoTabStrip .tabStripeOff a.tabsLink:visited {display:block;cursor:pointer;white-space:nowrap;color:#888;margin:0 4px 0 4px} div#cscoTabStrip .tabStripeOff a.tabsLink:hover {color:#f70} div#cscoTabStrip .tabStripeOn a.tabsLink, div#cscoTabStrip .tabStripeOn a.tabsLink:link, div#cscoTabStrip .tabStripeOn a.tabsLink:visited {display:block;cursor:pointer;white-space:nowrap;color:#000;font-weight:bold;margin:0 4px 0 4px} div#cscoTabStrip .tabStripeOn a.tabsLink:hover {} div#cscoTabStrip .tabLeftFirstOff {display:block;width:20px;height:35px;background:url(tabstrip/tabLeftFirstOff.png) no-repeat;} div#cscoTabStrip .tabLeftFirstOn {display:block;width:20px;height:35px;background:url(tabstrip/tabLeftFirstOn.png) no-repeat;} div#cscoTabStrip .tabMiddleOffOff {display:block;width:20px;height:35px;background:url(tabstrip/tabMiddleOffOff.png) no-repeat;} div#cscoTabStrip .tabMiddleOffOn {display:block;width:20px;height:35px;background:url(tabstrip/tabMiddleOffOn.png) no-repeat;} div#cscoTabStrip .tabMiddleOnOff {display:block;width:20px;height:35px;background:url(tabstrip/tabMiddleOnOff.png) no-repeat;} div#cscoTabStrip .tabStripeOff {background:url(tabstrip/tabStripeOff.png) repeat-x;} div#cscoTabStrip .tabStripeOn {background:url(tabstrip/tabStripeOn.png) repeat-x;} div#cscoTabStrip .tabRightLastOff {display:block;width:20px;height:35px;background:url(tabstrip/tabRightLastOff.png) no-repeat;} div#cscoTabStrip .tabRightLastOn {display:block;width:20px;height:35px;background:url(tabstrip/tabRightLastOn.png) no-repeat;} div#cscoTabStrip .topBG {text-align:right;background:url(tabstrip/topBg.png) repeat-x;} div#cscoTabStrip .tabStripContent {width:100%;padding:0;} div#cscoTabStrip .tabStripContentHidden {display:none;} |
Il codice Javascript è assai blando, scritto in un’epoca lontata quando Prototype.js non esisteva. Inoltre nell’esempio qui sotto faccio uso di una libreria di effetti (non esisteva nemmeno Scriptaculous) ancora valida, quindi la riga che usa la transizione Opacity la potete sostituire con quello che volete:
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 | function _onTabStrip(t) { if( arguments.length > 1 ) { var evt = "onBeforeClick"; var n = t.id.substr(7); var e = "var res = "+arguments[1]+"('"+n+"','"+evt+"');"; eval(e); if(!res) return(false); } var tr = t.parentNode.parentNode; for(var i = 1; i < tr.childNodes.length-2; i++ ) { var td = tr.childNodes[i]; var el = td.childNodes[0]; // switch( el.tagName ) { case "DIV": el.className = "tabMiddleOffOff"; break; case "A": td.className = "tabStripeOff"; break; } } var td = t.parentNode; td.previousSibling.childNodes[0].className = "tabMiddleOffOn"; td.nextSibling.childNodes[0].className = "tabMiddleOnOff"; tr.childNodes[0].childNodes[0].className = ( tr.childNodes[1].childNodes[0] === t )?"tabLeftFirstOn":"tabLeftFirstOff"; var last = Number( (tr.childNodes.length-2) ); tr.childNodes[last].childNodes[0].className = ( tr.childNodes[last-1].childNodes[0] === t )?"tabRightLastOn":"tabRightLastOff"; t.parentNode.className = "tabStripeOn"; var mc = $G( "jscoTSC_"+t.id ); var d = mc.parentNode; for (var i = 0; i < d.childNodes.length; i++) { d.childNodes[i].className = "tabStripContentHidden"; } mc.className = "tabStripContent"; var to = new OpacityTween(mc,Tween.regularEaseOut, 0, 100, 1); to.t = t; to.args = arguments; to.onMotionFinished = function() { if( this.args.length > 1 ) { var evt = "onAfterClick"; var n = this.t.id.substr(7); var e = "var res = "+this.args[1]+"('"+n+"','"+evt+"');"; eval(e); } }; to.start(); } |
In pratica le righe dalla 36 alle 46 possono essere sostituite con quello che volete, anche un display=”none”. Il codice è antiquato, almeno rispetto le nuove tecniche di Javascript non intrusivo (oggi lo scriverei in modo diverso). Tuttavia la parte che rimane interessante ed attuale e la configurazione della tabella HTML che gestisce i Tabstrip. Essa permette una resa grafica di alto livello, a differenza di alcuni altri metodi che – in sostanza – trattano le schede Tab come semplici DIV uno accanto all’altro.
Un modo ancora migliore sarebbe quello di sfruttare lo z-index (ordine di visualizzazione) presente negli stili CSS, così da gestire la sovrapposizione di elementi grafici. Purtroppo, ad oggi, è una tecnica assai difficile da implementare a causa delle differenze tra i browser che la rendono di fatto instabile, salvo rare circostanze.
Presto ne farò una versione più moderna… se avete dubbi o domande sono qui!









7
Ciao, cercando nel web ho trovato questo tuo articolo nel creare tabstrip con php javascript e css, ma provandolo ho un errore, selezionando qualsiasi tab continuo a visualizzare solo ed esclusivamente il contenuto del tab in cui ho settato “true” come default . Hai qualche suggerimento??
grazie, Fabio
@Fabio: un post del passato! Ti consiglio di utilizzare le più comode funzioni di tab oggi presenti, all’epoca non esisteva granché. La parte relativa alla costruzione grafica può essere ancora utile, ma per il codice ti consiglio di vedere jQuery ad esempio, o altre librerie simili.
Quando ‘scrissi’ questo post non ricordo bene nemmeno quali browser erano disponibili! Oggi rifarei tutto in modo assai diverso. Sono quasi sicuro – perché di solito controllo il codice che propongo – che all’epoca funzionava. L’errore che hai riscontrato potrebbe dipendere da tanti fattori; mia distrazione nel riportare qualche passaggio o, quasi certamente, il tempo ormai trascorso per questo articolo. Guarda jQuery UI che permette un’implementazione semplice e rapida dei tab strip, se hai necessità urgente. Saluti.