Sie sind auf Seite 1von 8

Alternative Style: Working With

Alternate Style Sheets


by Paul Sowden November 02, 2001
Published in CSS, HTML, JavaScript

Soyouvegotawebpage.YouvemarkeditupwithstructuralXHTML.Youvealsobeena
goodlittlewebdeveloperandusedstylesheetstocontrolwhatyourdocumentlookslike.
Youveevengonetheextramileandcreatedseveralalternativestylesheetstoshowhow
hardcoreyouare.
Great.Butnowyouneedacrossbrowserwaytodynamicallyswitchbetweenthestyle
sheets.

Styling your site


Stylesheetscanbeassociatedwithdocumentsusingalistoflinkelementsinthehead.
Therearethreedifferentrelationshipsexternalstylesheetscanhavewiththedocument:
persistent,preferred,andalternate.
PERSISTENT
Thesestylesheetsarealwaysenabled(theyarealwayson)andarecombinedwiththe
activestylesheet.Theycanbeusedforsharedrulescommontoeverystylesheet.Tomake
astylesheetpersistent,therelattributeissettostylesheetandnotitleattributeisset.
Tomakethestylesheet persistent,thefollowinglinkelementwouldbe
includedinthehead:




PREFERRED

Thesestylesheetsareenabledbydefault(theyareonwhenthepageisloaded).They
canthenbedisablediftheuserselectsanalternatestylesheet.
Tomakeastylesheetpreferred,the attributeissettostylesheetandthestylesheet
isnamedwiththe attribute.
Severalpreferredstylesheetscanbegroupedtogetherbygivingthemidenticaltitle
attributes.Thesegroupedstylesheetsarethenallenabledanddisabledtogether.Ifmore
thanonegroupofpreferredstylesheetsaredeclared,thefirstgrouptakesprecedence.
Tomake preferred,atitleattributeisadded,givingthedefaultstyleaname.





ALTERNATE
Thesestylesheetscanbeselectedbythevisitorasalternativestothepreferredstylesheet.
Thisallowsthevisitortopersonalizeasiteandchoosehisorherfavoritescheme.They
canalsobeusedforaccessibility.
Tospecifyanalternatestylesheet,therelattributeissettoalternatestylesheetandthe
stylesheetisnamedwithatitleattribute.Aswithpreferredsheets,thesestylesheetscan
alsobegroupedtogetherbygivingthemidenticaltitleattributes.
Usingthepreviousexampleagaintomake intoanalternatestylesheet,the
keywordalternateisaddedtotherelattribute.




Notethattheserelationshipsonlyapplytoexternalstylesheetswhichareincludedusing
thelinkelement.

Swappin Styles
Whenadocumentisinitiallyloaded,thepersistentandpreferredstylesheetsareapplied
tothedocument.Thealternatestylesheetscanthenbeselectedbytheuser.TheW3Ctells
usthatthebrowsershouldgiveusachoiceofthestylesheetwewanttouse,andsuggests
thatperhapsadropdownmenuortoolbarwillbeprovided.

Sofar,sogood.Wehaveseveralstylesheetsandthevisitorcanchoosetheirfavoritefrom
amenu.Butthenweencounteraproblem.Amajorone.Mozillaprovidesamenutoselect
thestylesheetwewanttouseundertheviewmenuitem.ButMicrosoftInternetExplorer
(MSIE)providesnosuchmenu.Sowehaveseveralstylesheets,andnowaytoaccess
theminMSIE.
HereswherealittlebitofJavaScriptcanbeusedalongwiththeDOMtoprovideawayfor
MSIEandMozillauserstoselectthestylesheettheywanttouse.Theirpreferencecan
alsobestoredinacookie.AndbecauseweareusingthelinktagsastheW3Ctellsusto,
theJavaScriptdoesntinterferewiththemenuinMozilla,anditdegradesverygracefully.

The Script
Firstweneedthescripttobeabletodifferentiatebetweenthethreedifferenttypesofstyle
sheet.Thisisrelativelyeasytodo,asweonlyneedtochecktwooftheattributesofeach
linkelement.
Isitalinktoastylesheet?


Isthereatitleattribute?


Doestherelattributecontainthekeywordalternate?


Notethatwecheckforthestringaltbecausesomebrowsersacceptthekeyword
alternativeinplaceofalternate.
Usingthesethreecheckswecanwriteafunctiontoswitchstylesheets.Thisinvolves
loopingthrougheverylinkelementinthedocument,disablingallpreferredandalternate
stylesheetsthatwedontwantactive,andenablingallpreferredandalternatestylesheets
thatwedowantactive.
Notethatonlypreferredandalternatestylesheetlinkelementswillhaveatitleattribute.
Thechangefunctionlookslikethis:











COOKIES
Nowwecanchangethestylesheet.Cool.Wehaveamorepersonalizedpage.Excellent.
Butwedonthaveapersonalizedsite.Thepreferenceisonlyappliedtothecurrentpage
whenweleavethecurrentpagethepreferenceleaveswithus.Thissituation,however,can
berectifiedwithacookie.
Tostoreacookieweneedanotherfunctiontoreturnthecurrentstylesheet.Wealsoneed
twofunctionstostoreandreadthecookie.
Toreturnthecurrentstylesheetwelookforanactivepreferredoralternatestylesheet
andcheckitstitle.
Firstweloopthroughallthelinkelementsinthedocumentagain.Wethencheckwhether
thelinkisastylesheet.Ifitis,wecheckwhetherthestylesheethasatitle.Thistellsus
thatthestylesheetiseitherpreferredoralternative.
Thelastcheckistoseewhetherornotthestylesheetisactive.Ifallthreechecksreturn
true,wehavethecurrentstylesheetandwecanreturnthetitle.
Thefunctionendsuplookinglikethis:












Asthisisanarticleonstyle,andcookiesareacompletelydifferenttopic,Iwontexplain
thecookiefunctionshere,butIwillincludethemforyourconvenience(thesefunctions
arewrittenbyALAauthorPeterPaulKoch(http://www.quirksmode.org/)).























Tousethesecookiefunctions,weneedtoadd and eventlisteners


(/articles/domtricks2/)tothewindow.
ONLOAD
Thereisaw3cspecifiedDOMLevel2attribute,disabled,thatissettofalsewhenastyle
sheetisappliedtothedocument.ThisattributeiscorrectlyimplementedinMozilla,but
unfortunatelynotinMSIE.

MSIEdoeshaveaproprietaryHTMLattribute,alsocalleddisabled,thatappliestolink
elements.Thisattributeisinitiallysettofalseforalllinkelements.
TosettheMSIEdisabledattributetomatchtheDOMLevel2disabledattribute,wecan
callthesetActiveStyleSheet()functionwiththenameofthepreferredstylesheet.
Tofindoutwhichstylesheetisthepreferredstylesheet,weneedanotherfunction.
Becausethisfunctionissosimilartothe  functionImnot
goingtoexplainhowitworks,buthereiswhatitmaylooklike:












Intheonloadfunction,wefirstsetatitlevariable.Thiseitherholdsthevalueofthe
previousstylesheetthatisstoredinthecookie,orifthereisntone,thetitleofour
preferredstylesheet.Tokeepthingslogical,letscallthecookiestyle.
Nextwecallupthe  functionpassingthetitlevariableasthe
title.Ouronloadfunctionlookssomethinglikethis:







Notethatitmaybedesirabletocallthisfunctionbeforetheonloadeventaswell,causing
thedocumenttopaintwithourstylesheetpreference.

Ifyouchoosetodothis,makesurethefunctioniscalledafterthefunctionsandthelink
elementshavebeendefined.
ONUNLOAD
Tosavethecookieintheonunloadeventissimpler.Allwehavetodoisusethe
 functiontoreturntheactivestylesheet,andsavethisina
cookie.Usingthefunctiontostoreacookiewewillendupwithsomethinglikethis:






Puttin it all together


Tousethesefunctionstomakeyourwebsitemoresexy,youneedtoincludetheminyour
document.Tomakeiteasy,Ihaveputthemalltogetherinajavascriptfile,readyforyou
todownload(/d/alternate/styleswitcher.js)andaddtoyoursite.
Download styleswitcher.js
Toincludethejavascriptfile,youaddascriptelementtotheheadofyourdocument,
makingsurethatitisputbelowallthestylesheetlinkelementsyouhave.TheHTML
wouldlooklikethis:



Toallowthevisitortochangetheactivestylesheet,youcouldusejavascriptonClick
events.Forexample,tohavetheoptiontoswitchbetweentwothemeswithtitlesdefault
andpaul,youcouldusethefollowingHTML:


Oncethevisitorhasselectedatheme,itwillbestoredinacookie.Tousethesametheme
throughoutyourwebsite,thesamestylesheetandjavascriptlinkelementsshouldbe
includedintheheadofeverypageofthesite.
THATS ALL, FOLKS!

Thereyouhaveit,acustomizablewebsitethatuseslinkelementstolinktostylesheetsas
theW3Chastoldusweshould.Enjoy!

About the Author


Paul Sowden
PaulSowden(http://www.idontsmoke.co.uk/)isateenagerfromLondon,England.Hebelievesthe
webwouldbeabetterplaceifeveryoneusedstandardscompliantdesigntechniques.

Issue

126
ISSN 1534-0295 Copyright 19982015 A List Apart & Our Authors

Das könnte Ihnen auch gefallen