Tải bản đầy đủ - 0 (trang)
Chapter 10. Dynamic Web Page Graphics

Chapter 10. Dynamic Web Page Graphics

Tải bản đầy đủ - 0trang

IuseJavaScriptinthisbook,butthepropername

isECMAScript,sincethisscriptinglanguageis

nowanECMAspecification.

Figure10-1.ScreenshotoftheBubblemarkDHTMLpage



10.1.TheQuickIntrototheDOM

Webpagesarebasedonastructureinwhichelementsare

nestedwithinelements:



Title



Thisisaparagraph.







Figure10-2containsascreenshotofanSVGdocument

(webstructure.svg,includedinthebookexamples)thatmaps

theHTMLelementsfromExample10-1intoatree-like

structure.Noticehowthetextcontainedwithinelementssuch

astitleandparealsonodeswithinthetree?Thereasonis

becausethecontentbetweenanelement'sopeningandclosing

tagsisalsoauniquepieceofthepage,separatefromandin

additiontotheelementsthemselves.

Figure10-2.AnSVGmappingofthestructureofaweb

page



Example10-1.SimpleHTML4.01webpageto

demonstratethehierarchicalnatureofwebpages

CodeView:




"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">


traditionalobjectorientedsense



Allmarkup-basedspecsarebasedonthesametree-likestruc

XML,andsoon



































ThoughnotdemonstratedinExample10-1,elementsalsohave

oneormoreattributes,whicharepropertiesdefiningthe

appearanceandbehavioroftheelement.Forinstance,the

followingcodesnippetcontainsanimageelement,img,with

threeattributesset,id,alt,andsrc:





Someattributescanbeusedonlywithspecificelements,

whereasotherattributescanbeusedwithmost,ifnotall,

elements.Thesrcattributecanbeusedonlywithsome

elements,suchasimg,buttheidattributeisuniversal.

Thewholedocumentstructureisgovernedbysomebasicrules,

suchasendingwhatisknownasanemptyelementwitha

forwardslash:





Anemptyelementisonethatdoesn'thavebothopeningand

closingtags,unlikethefollowing:

Title





Anotherruleisthatallelementsthataren'temptymusthave

closingtags,regardlessofwhethertheycontainanything,

thoughnotallvariationsofwebpagespecificationsrigidly

enforcetherules.

Youprobablyknowallofthisfromearlierchaptersoryourown

experiencesbeforepickingupthisbook.Thepointis,anyweb

pagecanbebrokendownintobasiccomponentsconsistingof

elements,content,andattributes,regardlessofthe

specificationgoverningthepage:XHTML,HTML,oreven

HTML5,currentlyunderdevelopment.Forourpurposes,

whatevercanbemodeledasaseparateanduniqueelementin

thepagecanbeaccessedusingJavaScript.

EveryelementinawebpageisaccessibleviaJavaScript,and

notjustthevisualelementsyousee,suchasthedivsanduls

andstylesheets.Eventhemetaelementsintheheadsectionof

thedocumentcanbeaccessedasanodeofthetreeformedby

alloftheelements,containedinwhatisknownastheDOM.



10.1.1.Enter:TheDOM

TheDocumentObjectModel(DOM)isaprogramminginterface

specificationcreatedbytheW3Cthatallowsustoaccessthe

elementsofawebpageprogrammatically.Therearethree

differentDOMspecifications:DOMLevel1,DOMLevel2,and

DOMLevel3,witheachnewlevelbuildingonthespecification

inthepreviousone.TheaspectoftheDOMwe'reconcerned

withinthischapteristhefunctionalityimplementedinbrowsers

thatallowsusprogrammaticaccesstothepageelementsand

theirattributes.

Implicitwithineverydocument,beitSVG,XML,orHTML,are

twoelementskeytoworkingwithawebpage'scontents:

windowanddocument.Thewindowobjectistheoverallparent,

andincludesthingslikethechromeandnavigation,aswellas

eventssuchasthosethatarefiredwhenthewebpageis

loaded.Thedocumentobjectencapsulatesalloftheelements

withinthedocument,suchasthebody,divs,andsoon.It's

throughthedocumentthatwecanaccesselementseitherbya

givenclassortype,oruniquely,byidentifier.

Focusingforthemomentonaccessingspecificpageelements,

toensurethatanelementisuniquelyaccessible,you'llneedto

givetheelementanidentifier:



...





Thedocumentmethodtoaccesstheelementis

getElementById,asfollows:

varcontents=document.getElementById("contents");



Nowyouhaveanactualrepresentationofthatelementwithin

thescript,readytomanipulateinallsortsofways.Onesuch

manipulationistoaccessand/oralterattributes.TwoDOM

methodscanbeusedtobothsetandretrieveanelement's

attributes:setAttributeandgetAttribute.

varattr=div1.getAttribute("id");

div1.setAttribute("class","test");



ThegetAttributemethodtakesoneparameter,thenameof

theattribute.ThesetAttributemethodtakestwo,oneforthe

attributenameandonefortheattribute'snewvalue.

Withjustthesethreemethods,getElementById,

setAttribute,andgetAttribute,youcancreateasurprising

numberofgraphicaleffects,simplybymodifyingoneattribute:

style.



10.1.2.WorkingwithCSSStyleSettings

Oneattributesharedbyallthevisualelementsisthestyle

attribute.Eveniftheattributeisn'texplicitlysetwithinthe

elementdirectly:





EveryelementhasaCSSstyle.

ThestyleattributecontainsareferencetotheCSSproperties

thatcanbemodifiedbyscript,suchasstyle.colorforfont

colororstyle.backgroundColorfortheelement'sbackground

color.Formultiple-wordproperties,suchasbackground-color

orfont-family,thepropertyisconvertedintoanotationthat

removesallofthedashes,andreplacesthelowercaseletterin



thewordfollowingthedashwithacapitalletter.Forexample:

background-colorbecomesbackgroundColor

font-familybecomesfontFamily

list-style-typebecomeslistStyleType

ThisnotationiscommonlycalledCamelCase,becauseofthe

up/downnatureofthenames,similartothehumpsofacamel.

EarlierImentionedthreeimportantDOMmethods:

getElementById,setAttribute,andgetAttribute.Inthe

webpageinExample10-2,theouterdivelementisstyled

withinthestylesheetembeddedintotheheadsectionofthe

document.Thepagealsohasasmallscriptingblockthat

doesn'tdoanythingmorethanaccessthestyleattributeand

changethebackgroundcolor.

Example10-2.Simplewebpagewithscripttoalterthe

backgroundcolorofoneoftheelements

CodeView:




"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">



#first

{

background-color:#ff0000;

}





//
window.onload=function(){



vardiv1=document.getElementById("first");

vardiv1style=div1.getAttribute("style");

div1style.backgroundColor="#ffff00";

}

//]]>









Thetextofthefirstparagraph





Thename"DocumentObjectModel"waschosenbecauseitisan

traditionalobjectorientedsense



Allmarkup-basedspecsarebasedonthesametree-likestruc

XML,andsoon



































Iloadthepageinthebrowser,confidentthatthecolorofthe

backgroundforthefirstdivelementwillbechanged,onlyto

receiveaJavaScripterrordisplayedintheFirefoxextension

Firebug,asshowninFigure10-3.

Figure10-3.JavaScripterrorreflectedintheFirebox

debuggingwindow



Example10-2generatedtheerrorbecausethereisno

backgroundcolorstylesettingtotheapplication.Thoughthe

backgroundcolorissetusingastylesheet,thispropertyisnot

availabletoscriptuntileitherit'ssetdirectlyinscript,first,

orsetwithinastyleattributeaddeddirectlytotheelement.

Evenwiththelatter,youcanaccessthestyleattributeonthe

element,butallyou'llgetisastringcontainingalloftheCSS

properties—notindividuallyaccessibleCSSattributes.

Thereasonthebackgroundcolorisn'taccessibleviascriptin

thiswebpageisbecausethestylesettingusedtorenderthe

divelementisacomputedsetting,consistingofacombination

ofstylesheetsettings,elementinheritance,andbrowser

defaults.Assuch,they'renotsomethingyoucanjustaccess

directlyfromthestyleattribute.

CSSstylepropertiesareblankorundefined

exceptwhensetpreviouslyinthescript,evenif



yousetthevaluethroughastylesheetorsetthe

styleattributedirectlyintheelement.



ToreadindividualCSSstyleproperties,you'llneedtouseother

properties,eachspecifictodifferenttypesofbrowsers.Internet

Explorer(IE)andOperasupportacurrentStylepropertyon

theelement,thoughhowthevalueisaccesseddiffersbetween

thetwo.ThecurrentstyleisanarrayvaluewithIE,whereas

OperasupportstheDOM-compatiblegetPropertyValue

method.FirefoxandSafarisupportwindow.getComputedStyle,

whichthenreturnsanobjectfromwhichwecanderivetheCSS

styleusinggetPropertyValue.

Wecouldaccountfordifferencesinstyleaccessamong

browsersifthisweretheonlydifference.Unfortunately,it'snot.

ForthegetPropertyValuemethods,regardlessofhowyouget

theobjectthatsupportsthismethod,youmustpassintheCSS

attributeusingthesamesyntaxyouusewhensettingthestyle

inthestylesheet.Inotherwords,sayyouusebackgroundcolortoaccessthebackgroundcolor.However,fortheIEspecificcurrentStylearraymethod,you'llusetheCamelCase

notation,describedearlier:backgroundColorratherthan

background-color.

Asthisbookwasbeingpreparedforpublication,

MicrosoftreleasedthefirstbetaofIE8,which

addressessomeofthebrowserdifferences

betweenIE8andtheotherbrowsers.Aslongas

JavaScriptlibrariesuseobjectdetection(looking

foraspecificmethodorproperty),thelibrary

shouldworkequallywellwithIE7andIE8andthe

otherbrowsers.



Inordertoworkaroundthebrowserdifferences,developers

typicallycreatefunctionsthatcheckfortheexistenceofspecific

functionalitywithwhichtoaccessthestyleproperty.Ifone

methodisn'tsupported,asecondistested,andsoonuntilall

browserdifferenceshavebeenaccountedfor.That'sthe

approchwe'lluse.InExample10-3,anewfunctioniscreated,

getStyle,takingthreeparameters:theelementwhoseCSS

stylewe'retryingtofind,thestylepropertynameinCSS

format,and,finally,thepropertynameinCamelCasenotation.

ThefunctionteststoseewhethercurrentStyleissupported,

andthenwhethergetPropertyValueissupported,andpulls

thevaluebasedontheresponse.ForcomputedStyle,the

functionusesthesametestforanappropriateresponse.Finally,

onelasttestismade:toseewhetherthepropertyisactually

setinthestyleattribute.

Example10-3.Usingacross-browserCSSstyletechnique

CodeView:




strict.dtd">



#first

{

background-color:#ff0000;

color:#fff;

}





//
functiongetStyle(node,styleName,camelStyleName){



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Chapter 10. Dynamic Web Page Graphics

Tải bản đầy đủ ngay(0 tr)

×