String and Number Objects (Chapters 34 and 35)

Một phần của tài liệu tài liệu hướng dẫn sử dụng javascript (Trang 540 - 586)

C hapter 31 of the JavaScript Bible is devoted to positioned objects in all object models. Only Navigator 4 has its own set of dedicated positionable objects: the LAYER and ILAYER element objects. In the IE4+ and W3C DOMs, v irtu a lly any renderable element is positionable, although it is common practice to re strict such a ctivity to SPAN and DIV elements.

Because properties of the SPAN, DIV, and other HTML element objects are covered in detail in other chapters, Chapter 31 provides the details of the NN4 layer object.

Examples shown here support NN4 layer object details, but the rest of the discussion and code listings in JavaScript Bible Chapter 31 go to great lengths to recreate the same behaviors in both the IE4+ and W3C (NN6) object models. This w ill help those scripters who developed extensively for NN4’s Dynamic HTML make the transition to NN6 and its support for Dynamic HTML (w hich is not much different from that in the IE4+ object model). Obviously, all examples shown below require NN4.

Examples Highlights

♦ Clipping of layer rectangles is not an easy concept to grasp at firs t (in any object model). Listing 31-2 provides a workbench to explore the various properties associ­

ated w ith the clipping rectangle. Listing 31-5 demon­

strates the relationship between moving a layer and adjusting its clipping rectangle.

Listing 31-6 is an extensive dem onstration of a va rie ty of layer coordinate system properties.

♦ Most layer object properties are handled in later object models through style sheet p ro pe rty m anipulation.

Listing 31-8 shows the NN4 layer way of handling a layer’s visib ility, w hile Listing 31-9 demonstrates adjust­

ing the stacking order of layers.

1 5

4- 4-

In This C ha p te r Using N N 4-specific syntax for positioned elements

How to move, hide, and show positioned content in N N 4 Setting the clipping rectangle of a layer in N N 4

♦ 4- ♦ ♦

4 4 2 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Scripts for dragging a layer (w ith the help of the layer object’s move methods) appear in Listing 31-11. Another type of dragging— dragging a corner to resize a la y e r— takes center stage in Listing 31-12a.

NN4 Layer Object

Properties

above bel ow

si bli ngAbove si bli ngBelow

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility

Example

Listing 31-1 enables you to experiment w ith just one set of these properties:

1 a y e r O b j e c t .a b o v e and 1 a y e r O b j e c t .bel ow. The page is almost in the form of a laboratory/quiz th a t enables you to query yourself about the values of these prop­

erties fo r tw o swappable layers.

Listing 31-1 : A Layer Quiz

<HTML>

<HEAD>

<SCRIPT LANGUAGE“ "JavaScript">

function checkAbove(oneLayer) { document.forms[0] .errors .val ue =

document.forms[0].output.value = oneLayer.above.name )

function checkBelow(oneLayer) { document.forms[0] .errors.value =

document.forms[0].output.val ue = oneLayer.below.name }

function swapLayersO (

if (document.yeller.above) {

document.yeller.moveAbcve(document.greeny) ) else {

document.greeny.moveAbcve(document.yel1er) )

)

docum ent JayerObject.above

Chapter 15 ♦ The NN4 Layer Object (Chapter 31) 4 4 3

function onerror(msg) (

document.forms[0].output.value = ""

document.forms[0].errors.va 1 ue = msg return true

}

</SC RIPT>

</HEAD>

<B0DY>

<Hl>Layer Ordering</Hl>

<HR>

<F0RM>

Results:<INPUT TYPE="text" NAME="output"XP>

< INPUT TYPE="button" VALUE-'Whc’s ABOVE the Yellow layer?"

onClick="checkAbove(document.yel1er)"><BR>

< INPUT TYPE="button" VALUE-’Whc’s BELOW the Yellow layer?"

onCl ick="checkBelow(document.yel1er)"><P>

<1NPUI IYPt=”button" VALUL="Whc’s ABOVE the Green layer?”

onCl i ck="checkAbove( document .greeny) " X B R >

< INPUT TYPE="button" VALUE=”Whc’s BELOW the Green layer?”

onCl ick=”checkBelow(document.greeny)"><P>

< INPUT TYPE-"button" VALUE=”Swap Layers" onCLick="swapLayers()"XP>

If there are any errors caused by missing <BR>

properties, they will appear below:<BR>

<TEXTAREA NAME=”errors" C0LS=3C R0WS=3 WRAP-'vlrtual"X/TEXTAREA>

</F0RM>

<LAYER NAME="yel 1 er" BGC0L0R=”ye1low” T0P=110 LEFT=300 WIDTH=200 HEIGHT=200>

<B>This is just a yellow layer.</B>

</LAY ER>

<LAYER NAME-"greeny" BGCOLOR="lightgreen” T0P=150 LEFT=340 WIDTH=200 HEIGHT=200>

<B>This is just a green layer.</B>

</LAYER>

</B0DY>

</HTML>

The page contains tw o layers: one colored yellow and the other light green.

Legends on four buttons ask you to guess w hether one layer is above o r below the other. For example, if you click the button labeled “W ho’s ABOVE the Yellow layer?”

and the green layer is above it, the name of tha t green layer appears in the Results field. But if layers are oriented such tha t the returned value is n u l l, the e rror mes­

sage (indicating tha t the nonexistent object doesn’t have a n a m e property) appears in the e rror field at the bottom . Another button enables you to swap the order of the layers so you can tr y yo ur hand at predicting the results based on yo ur know l­

edge of layers and the a b o v e and be! o w properties. Positioned objects in IE4+ and NN6 have no comparable properties to the four described in this section.

docum ent./ayerO A /ecf.above

4 4 4 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

background

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

Compatibility ✓

Example

A simple example (Listing 31-2) defines one layer th a t features five buttons to change the background image of a second layer. I put the buttons in a layer because I w ant to make sure the buttons and background layer rectangles align themselves along th e ir top edges on all platforms.

As the second layer loads, I merely assign a gray background color to it and w rite some reverse (w hite) text. Most of the images are of the small variety that repeat in the layer. One is a large photograph to demonstrate how images are clipped to the layer’s rectangle. Along the way, I hope you also heed the lesson of readability dem onstrated by the d iffic u lty of reading text on a wild-looking back­

ground. For an example compatible w ith IE5+ and NN6+, see Listing 31-13.

Listing 31-2: Setting Layer Backgrounds

<HTML>

<HEAD>

<SCRIPT LANGUAGE“ "JavaScript">

function setBg(URL) {

document.bgExpo.background.src = URL }

</SCRIPT>

</HEAD>

<B0DY>

<Hl>Layer Backgrounds</Hl>

<HR>

<LAYER NAME="buttons" T0P=100>

<F0RM>

< INPUT TYPE="button" VALUE="The Usual"

onCl ick="setBg('cr_kraft.gif')"><BR>

< INPUT TYPE="button" VALUE=”A Big One" onClick="setBg('arch.gif')"><BR>

< INPUT TYPE="button" VALUE="Not So Usual"

onClick="setBg('wh86.gif')"><BR>

< INPUT TYPE="button" VALUE="Decidedly Unusual"

onClick="setBg('sb23.gif')"><BR>

< INPUT TYPE="button" VALUE="Quick as..."

onClick="setBg('lightnin.gif')"><BR>

</F0RM>

</LAYER>

< LAYER NAME="bgExpo" BGC0L0R=”cray" T0P=100 LEFT=250 WIDTH=300 HEIGHT=260>

< B X F 0 N T C0L0R="white">Some text, which may or may not read well with the various backgrounds.</F0NTX/B>

docum ent JayerObject.backgiound

Chapter 15 ♦ The NN4 Layer Object (Chapter 31)

</LAYER>

</B0DY>

</HTML>

bgColor

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility

Example

You can have some fun w ith Listing 31-3, w hich uses a num ber of layer scripting techniques. The page presents a kind of palette of eight colors, each one created as a small layer (see Figure 15-1). Another, larger layer’s b g C o l o r p roperty changes as you ro ll the mouse over any color in the palette.

N etscape

Fite Edit View Go Communicator Help

^ •£ 3 4k 4* st £ 11

Back iV 'A '.rd Reload Home Search Guide Piint Security

Layer Background Colors

Some reversed text to test against background colors.

nỉ Document: Done

Figure 15-1: Drag the mouse across the palette to change the layer's background color.

To save HTML lines to create those eight color palette layers, I use a scrip t to establish an array of colors and then d o c u m e n t .wri t e () the < L A Y E R > tags w ith appropriate a ttribu te settings so the layers all line up in a contiguous row. By pre­

defining a num ber of variable values for the size of the color layers, I can make all of them larger o r smaller w ith the change of only a few scrip t characters.

The d o c u m e n t object handles the job of capturing the m o u s e O v e r events. 1 turn on the docum ent’s c a p t u r e E v e n t s ( ) method such that it traps all m o u s e O v e r

4 4 5

docum ent./aỵerO ử/ecỉ.bgColor

4 4 6 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

events and hands them to the sctCol or ( ) function. The sct Col or () function reads the target object’s bgCol or and sets the larger layer’s bgColor p ro p e rty to the same. If this page had other objects th a t could receive mouseOver events for other purposes, I would use r o u te E ve nt s ( ) to let those events pass on to th e ir intended targets. For the purposes of this example, however, the events need to go no further. Listing 31-14 in the JavaScript Bible shows the same functionality w ork­

ing in IE5+ and NN6+.

Listing 31-3: Layer Background Colors

<HTML>

<HEAD>

<SCRIPT LANGUAGE“ "JavaScript">

function setColor(e) {

document.display.bgColor = e.target.bgColor }

document.captureEvents(Event.MOUSEOVER) document.onmouseover = setColor

</SCRIPT>

</HEAD>

<B0DY>

<Hl>Layer Background Co1ors</Hl>

<HR>

<scRIPT LANGUAGE“ "JavaScript">

var oneLayer var colorTop = 100 var colorLeft = 20 var colorWidth = 40 var colorHeight = 40 var colorPalette = new

Array("aquamarine” ,"coraI” ,"torestgreen” ,"goIdenrod","red” ,

"magenta","navy","teal") for (var i = 0; i < colorPalette.length; 1++) {

oneLayer = "CLAYER NAME=swatch" + i + " T0P=" + colorTop oneLayer += ” LEFT“ " + ((cclorWidth * i) + colorLeft)

oneLayer += " WIDTH'" + colorWidth + " HEIGHT-" + colorHeight oneLayer += " BGCOLOR“ " + colorPalette[i] + "></LAYER>\n"

document.write(oneLayer) }

</SC RIPT>

<LAYER NAME="display" BGC0L0R=”gray" T0P=150 LEFT=80 WIDTH=200 HEIGHT=200>

< B X F 0 N T C0L0R="white"XCENTER>Some reversed text to test against background colors . < / C E N T ERX /FO NTX/B >

</LAYER>

</B0DY>

</HTML>

docum ent JayerObject.bgCo\oT

Chapter 15 ♦ The NN4 Layer Object (Chapter 31)

c l i p

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility

Example

Because of the edge movement behavior of adjustments to 7 ayer O bject . c l i p properties, Listing 31-4 enables you to experiment w ith adjustments to each of the six properties. The document loads one layer tha t you can adjust by entering alter­

native values into six text fields — one per property. Figure 15-2 shows the page.

Layer Clio - N e tscap e M i l 1 3 1

File £ dii View f io Communicator Help

■ J i -sfe- i i i k

Back F e n c 'd Reload Home

^ 4 i U BS1

Search Guide Piint Security c-op

L a y e r C li p p i n g P r o p e r t i e s

E n ter n e w clipping v a lu e s to ad ju st the visible a r e a o f the laye r.

la y e r, clip.left: [o A R T IC L E I

layer.clip .top: [o layer.clip .righ t: [ 3 6 0 la ye r.clip bottom . J i80

C o n g re ss shall m a k e .10 la w re sp e ctin g an establishm ent o f religion, or prohibiting the fre e e x e rc is e th e re o f; o r abnd ging the fre e d o m o f sp eech , or o f the p re s s , or the right o f the people p e a c e a b ly to assem b le, and to petition the govern m ent fo r a re d re s s o f g n e van c es.

la y e r clip, width: [360 la y e r, clip.height: J l80 R e v e a l O r ig in a l L a y e r

¿ p Document: Done f U a L x

Figure 15-2: Experiment with layer.clip properties.

As you enter values, all properties are updated to show th e ir current values (via the showVal ues ( ) function). Pay p articula r attention to the apparent m otion of the edge and the effect the change has on at least one other property. For example, a change to the 7 a y e r O b j e c t . c l ip . 1 e f t value also affects the 7 ayer Object . c l i p , w i d t h p ro pe rty value.

Listing 31-4: Adjusting layer.clip Properties

<HTML>

<HEAD>

<TITLE>Layer Clip</TITLE>

<SCRIPT LANGUAGE“ "JavaScript”>

var origLayerWidth = 0 var origLayerHeight = 0

Continued

4 4 7

document.layerObject.ciip

4 4 8 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Listing 31-4 (continued)

function initia 1izeXY() {

origLayerWidth = document.cisplay.clip.width origLayerHeight = document.display.clip.height showValues()

function setClip(field) {

var clipVal = parselnt(field.value)

document.display.clip[field.name] = clipVal showValues()

)

function showValues() (

var form = document.layers[0].document.forms[0]

var propName

for (var i = 0; i < form.elements.1ength; i++) { propName = form.elements[i].name

if (form.elements[i] .type == "text”) {

form.elements[i] .value = document.display.clip[propName]

) } )

var intervallD

function reveal Clip() (

var midWidth - Math.round(crigLayerWidth /2) var midHeight = Math.roundtorigLayerHeight /2) document.display.clip.left = midWidth

document.display.clip.top = midHeight document.display.clip.right = midWidth document.display.clip.bottom = midHeight intervallD = setlnterval("stepClip()", 1) }

function stepClip() { var widthDone = false var heightDone = false

if (document.display.clip.left > 0) { document.display.clip.left += -2 document.display.cl ip.right += 2 ) else {

widthDone = true )

if (document.display.clip.top > 0) { document.display.cl ip.top += -1 document.display.cl ip.bottom += 1 ) else {

heightDone = true )

showValues()

if (widthDone && heightDone) ( cl earInterval(interval ID)

document JayerO bject.dip

Chapter 15 ♦ The NN4 Layer Object (Chapter 31) 4 4 9

) }

</SC RIPT>

</HEAD>

<ES0DY onLoad="initializeXY( )">

<Hl>Layer Clipping Properties</Hl>

<HR>

Enter new clipping values to adjust the visible area of the layer.<P>

<LAYER T0P=130>

<F0RM>

<TABLE>

<TR>

<TD ALIGN="right">1ayer.clip.1 e f t :</TD>

< T D X I N P U T TYPE="text" NAME="left" SIZE=3 onChange="setCl ip(this)"X/TD>

</TR>

<TR>

< IU ALIGN“ ”right”>Iayer.clip.top:</IU>

< T D X I N P U T TYPE="text” NAME=”top" SIZE=3 onChange=”setCl ip(thi s ) nX / T D >

</TR>

<TR>

<TD ALIGN="right">layer.clip.right:</TD>

C T D X I N P U T TYPE="text" NAME-"right" SIZE=3 onChange=”setCl ip(this)"X/TD>

</TR>

<TR>

<TD ALIGN-"right”>layer.clip.bottom:</TD>

< T D X I N P U T TYPE="text" NAME=”bottom" SIZE=3 onChange=”setCl i pi thi s ) ”X / T D >

</TR>

<TR>

<TD ALIGN=”right”>layer.clip.width:</TD>

< T D X I N P U T TYPE=”text" NAME="width" SIZE=3 onChange-"setClip(this)"X/TD>

</TR>

<TR>

<TD ALIGN="right">layer.clip.height:</TD>

< T D X I N P U T TYPE="text” NAME="height" SIZE=3 onChange-"setClipithis)'X/TD>

</TR>

</TABLE>

< INPUT TYPE="button" VALUE="Reveal Original Layer" onClick="revealCl ip( )">

</F0RM>

</LAY E R>

<LAYER NAME="display" BGC0L0R="coral" T0P=130 LEFT=200 WIDTH=360 HEIGHT=180>

<H2>ARTICLE I</H2>

<P>

Congress shall make no law respecting an establishment of religion, or

prohibiting the free exercise thereof; or abridging the freedom of speech, or of the press; or the right of the people peaceably to assemble, and to petition the government for a redress of grievances.

</P>

</LAYER>

</B0DY>

</HTML>

docum ent./oyerOAyecf.clip

4 5 0 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Listing 31-4 has a lo t of other scrip tin g in it to dem onstrate a couple of other clip area techniques. A fter the document loads, the o n L o a d event handler initializes tw o global variables tha t represent the starting height and w id th of the layer as deter­

mined by the c l i p , hei g h t and cl i p . wi d t h properties. Because the < L A Y E R > tag does not specify any C L I P attributes, the 1 ayerObject . c l i p region is ensured of being the same as the layer’s dimensions at load time.

I preserve the in itia l values for a somewhat advanced set of functions that act in response to the Reveal Original Layer button. The goal of this button is to tem­

p o ra rily shrink the clipping area to nothing and then expand the clip rectangle gradually from the ve ry center of the layer. The effect is analogous to a zoom-out visual effect.

The clip region shrinks to practically nothing by setting all four edges to the same p o in t m idway along the height and w id th of the layer. The script then uses

s e t l n t e r v a l ( ) to control the animation in s e t c i i p (). To make the zoom even on both axes, I firs t make sure that the in itia l size of the layer is an even ratio: tw ice as wide as it is tall. Each tim e through the s e t c i i p ( ) function, the cl ip . 1 e f t and

cl i p . r i g h t values are adjusted in th e ir respective directions by two pixels and

cl i p. t o p and cl i p . b o t t o m are adjusted by one pixel.

To make sure the animation stops when the layer is at its original size, I check w hether the c l i p . to p and c l i p . 1 e f t values are th e ir original zero values. If they are, I set a Boolean variable for each side. When both variables indicate tha t the clip rectangle is its original size, the scrip t cancels the s e t l n t e r v a i o action.

Listing 31-15 in the .JavaScript Bible demonstrates how to adjust clipping in IE5+

and NN6+ syntax.

l e f t t o p

NN2 NN3 NN4 NN6 IE3/J1 IE3/J2 IE4 IE5 IE5.5

C om pa tib ility

Example

To enable you to experiment w ith manually setting 1 ayerObject. t op and 1 ayerO b j e c t . 1 e f t properties, Listing 31-5 is a m odified version of the 1 a y e r . cl i p example (Listing 31-4). The current example again has the one modifiable layer, but it has only four text fields in w hich you can enter values. Two fields are for the

/ayerO b j e c t. 1 e f t and 1 a yerO bject. to p properties; the other two are for the 1 a y e r O b j e c t. c l i p . 1 e f t and 1 a y e r O b j e c t. c l i p . to p properties. ] present both sets of values here to help reinforce the lack of connection between layer and clip location properties in the same layer object. You can find the corresponding syntax for IE5+ and NN6+ in Listing 31-16 of the JavaScript Bible.

docum ent JayerObjectAeft

Chapter 15 ♦ The NN4 Layer Object (Chapter 31) 4 5 1

Listing 31-5: Comparison o f Layer and Clip Location Properties

<HTML>

<HEAD>

<TITLE>Layer vs. Clip</TITLE>

<SCRIPT LANGUAGE“ ”JavaScript”>

function setClip(field) {

var clipVal = parselnt(field.value)

document.display.clipCfielc.name] = clipVal showValues()

)

function setLayer(field) {

var layerVal = parselnt(field.value) document..display[fie1rl.name] = layerVal showValues()

}

function showValues() (

var form = document.layers[0].document.forms[0]

form.elements[0].value = document.display.left form.elements[l].value = document.display.top form.elements[2].value = document.display.clip.left form.el ements[3].val ue = document.display.clip.top }

</SC RIPT>

</HEAD>

<B0DY onLoad="showValues()">

<B>Layer vs. Clip Location Properties</B>

<HR>

Enter new layer and clipping values to adjust the layer.<P>

<LAYER T0p=80>

<F0RM>

<TABLE>

<TR>

<TD ALIGN="right">layer.1 eft:</TD>

< T D X I N P U T TYPE="text" NAME="left" SIZE=3 onChange="setLayer(this)”X / T D >

</TR>

<TR>

<TD ALIGN="right">1ayer.top:</TD>

< T D X I N P U T TYPE="text" NAME="top" SIZE=3 onChange=”setLayer(this)”X / T D >

</TR>

<TR>

<TD ALIGN="right">layer.clip.left:</TD>

< T D X I N P U T TYPE="text" NAME="left" SIZE=3 onChange="setClip(this)”X / T D >

</TR>

<TR>

<TD ALIGN="right">layer.clip.top:</TD>

< T D X I N P U T TYPE="text” NAME="topn SIZE=3 onChange="setClip(this)"X/TD>

</TR>

</TABLE>

</F0RM>

Continued

¿ocument.layerObject.left

Một phần của tài liệu tài liệu hướng dẫn sử dụng javascript (Trang 540 - 586)

Tải bản đầy đủ (PDF)

(631 trang)