Navigator and Other Environment Objects (Chapter 2 8 )

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

m m \

A P T I

D ynam ic object models that take advantage of autom atic page reflow create huge opportunities for creative Web designers. Nowhere is th a t more apparent than in the TABLE element object and all the other objects that nest w ith in (TR, TH, TD, and so on). Not only is it possible to swap the content of a table cell at any time, but the object models provide pow­

erful methods for com pletely remolding the com position of a table on the fly.

HTML tables are at once elegant because they provide a lo t of pleasing organization to a page w ith little code, and also complex due to the large num ber of related elements and sub­

stantial lis t of attributes fo r each element. Those attributes become object properties in the modern object model, so it means th a t scripters have much to choose from (and be con­

fused by) when bringing tables to life.

Using the special-purpose methods that insert rows and cells also takes some in itia l adjustment fo r many scripters.

For example, inserting a row has almost no visual effect on an existing table u n til you not only insert cells into the row, but also plant content in the cells. Code examples for these opera­

tions are part of the general discussion of the TABLE object in the JavaScript Bible.

Designers whose browser targets are IE4+/Windows can also take advantage of M icrosoft’s data binding technology.

Data from external sources can fill tables w ith only the slight­

est b it of HTML markup. Chapter 15 contains examples of this in its discussion of the data FI d and related properties.

This chapter also includes objects fo r ordered and

unordered lists (and lis t items nested w ith in ). In concert w ith style sheets th a t can include o r exclude elements from page rendering, these objects provide additional layout o pp o rtun i­

ties fo r clever designers.

♦ ♦ ♦ ♦

In This Chapter

M odifying table cell content

A dding and deleting table rows

M odifying table dimensions, colors, and borders

Changing numbering sequences and bullet symbols for LI element objects

3 8 2 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Examples Highlights

♦ Scripts can adjust the value of a TABLE object’s wi d th property, including sw itching between a fixed pixel size and a percentage of the table container’s w idth.

♦ Compare the examples for the IE5/Windows TABLE.cells p roperty and the TR. cel 1 s p ro pe rty fo r IE4+ and NN6.

♦ Follow the example for the TD.colSpan p ro pe rty to observe how a table responds to such changes in real time.

♦ Examples for list-related elements show how to set the lis t types for scrip t­

generated lists.

TABLE Element Object

Properties

al i gn

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

Compatibility / s V V

Example

Use The Evaluator (Chapter 13 in the JavaScript Bible) to see the align p ro pe rty at work. The default value (1 eft) is in force when the page loads. But you can shift the table to right-align w ith the body by entering the follow ing statement into the top text box for IE5+ and NN6+:

d o c u m e n t .get E1emen tB yI d( "m yT ab le").a l ign = "right"

background

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

Compatibility / ✓ ✓

Example

Treat the background p roperty of a table like you do the s rc p roperty of an IMG element object. If you precache an image, you can assign the s rc p roperty of the precached i mage object to the background p ro p e rty of the table for quick image changing. Such an assignment statement looks like the following:

d o c u m e n t .al 1 .myTable.background = imgArray[''myTableAl t e rn at e”] .src

TABLE.background

bgColor

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

Compatibility / / / /

Chapter 11 ♦ Table and List Objects (Chapter 27)

Example

Use The Evaluator (Chapter 13 in the JavaScript Bible ) to assign a color to the table. A fter looking at the table to see its in itia l state, enter the follow ing IE5+/NN6+

statement into the top text box:

document.get ElementById("myTable").bgCol or = "1ightgreen"

When you look at the table again, you see th a t only some of the cells turned to green. This is because colors also are assigned to table elements nested inside the outerm ost table element, and the color specification closest to the actual element wins the contest.

border

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

Compatibility / / / ✓

Example

To remove all traces of an outside border of a table (and, in some com binations of attributes of other table elements, borders between cells), use the follow ing statement (in IE 5 + / N N 6 + syntax):

document.get El ementBy!d("myTable").border = 0

borderColor

borderColorDark borderColorLi ght

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

Compatibility / / ✓

Example

Assuming that you have set the in itia l lig h t and dark color attributes of a table, the follow ing function swaps the lig h t and dark colors to shift the light source to the opposite corner:

3 8 3

TABLE.borderColor

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

function swapColors(tableRef) (

var oldLight - tableRef.borderColorLight

tableRef.borderColorLight = tableRef.borderColorDark tableRef.borderColorDark = oldLight

}

While you can easily invoke this function over and over b y ending it w ith a

s e t T i m e o u t () method that calls this function after a fraction of a second, the results are ve ry distracting to the person try in g to read yo ur page. Please don’t do it.

capti on

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

Compatibility / / / /

Example

The follow ing example, for use w ith The Evaluator (Chapter 13 in the JavaScript Bible ) in NN6+, demonstrates the sequence of assigning a new CAPTION element object to a table. W hile the table in The Evaluator already has a CAPTION element, the follow ing statements replace it w ith an entirely new one. Enter each of the follow ing statements into the top text box, starting w ith the one that saves a long reference into a variable for m ultiple uses at the end:

t = document. getEiementByldC'myTable") a - document.createEleraenti"CAFTION")

b = document.createTextNode("A Brand New Caption") a.appendChild(b)

t.replaceChild(a, t.caption)

A view of the table shows that the new caption has replaced the old one because a table can have only one CAPTION element.

cel 1Paddi ng cel 1Spaci ng

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

Compatibility / / / ✓

Example

Use The Evaluator (Chapter 13 in the JavaScript Bible) to adjust the

cel 1 Paddi ng and cel 1 Spaci nc properties of the dem onstrator table. First, adjust the padding ỢE5+/NN6 syntax):

document.getElementBy!d("myTable").cel 1 Padding = 50

TABLE.cellPadding

Chapter 11 ♦ Table and List Objects (Chapter 27) 3 8 5

Now, adjust the cell spacing:

document.get ElementById("myTable").cel 1 Spacing = 15

Notice how cel 1 Spaci ng affected the thickness of inter-cell borders.

cel 1 s

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

Compatibility ✓ ✓

Example

Use The Evaluator w ith IE5+ for Windows to have JavaScript calculate the num­

ber of columns in the dem onstrator table w ith the help of the cel 1 s and rows properties. Enter the follow ing statement in to the to p text box:

document.all.myTable.cell s.lencth/document.all .myTable.rows, length The result is the num ber of columns in the table.

dataPageSi ze

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

Compatibility / / /

Example

If you want to change the number of visible rows of linked data in the table to 15, use the follow ing statement:

document.all.myTable.dataPageSize = 15

frame

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

Compatibility / / / /

Example

Listing 27-4 presents a page that cycles through all possible settings fo r the frame property. The frame p roperty value is displayed in the table’s caption. (Early versions of NN6 m ight fail to refresh p art of the page after adjusting the frame property.)

TABLE.frame

3 8 6 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Listing 27-4: Cycling Through Table frame Property Values

<HTML>

<HEAD>

<TITLE>TABLE.frame Property</TITLE>

<SCRIPT LANGUAGE“ "JavaScript">

var timeoutID

var frameValues = ["box", "above", "rhs", "below", "lhs", "hsides", "vsides",

"border", "void"]

function rotateBorder(i) {

document.get E1ementById("myTABLE").frame = frameValues[i]

document.getElementByldi"myCAPTION").i nnerHTML = frameValues[i]

i = (++1 == frameValues.lergth) ? 0 : i

timeoutID = setTimeout("rotateBorder(" + i + ")", 2000) )

function stopRotateO ( clearTimeout(timeoutID)

document.getElementByldi"myTABLE").frame = "box"

document.getElementById("myCAPTION").innerHTML = "box"

)

</SC RIPT>

</HEAD>

<B0DY>

<H1>TABLE.frame Property</Hl>

<HR>

<F0RM NAME="controls">

< FIE LDSET>

<LEGEND>Cycle Table Edge Visibil ity</LEGEND>

<TABLE WIDTH="100%" CELLSPACING=20XTR>

< T D X I N P U T TYPE="button" VALUE=”Cycle" onClick="rotateBorder(0)"X/TD>

< T D X I N P U T TYPE="button" VALUE="Stop" onClick="stopRotate()"X/TD>

</TR>

</TABLE>

</FIE LDS ET>

</TABLE>

</FIE LDS ET>

</F0RM>

<HR>

<TABLE ID="myTABLE" CELLPADDING=5 B0RDER=3 ALIGN="center">

<CAPTION ID="myCAPTI0N">Default</CAPTI0N>

<THEAD ID="myTHEAD">

<TR>

<TH>River<TH>0utf1ow<TH>Miles<TH>Ki1ometers

</TR>

</THEAD>

<TB0DY>

<TR>

<TD>Ni1e<TD>Mediterranean<TD>4160<TD>6700

</TR>

<TR>

<TD>Congo<TD>Atlanti c 0cear<TD>2900<TD>4670

TABLE.frame

Chapter 11 ♦ Table and List Objects (Chapter 27) 3 8 7

</TR>

<TR>

<TD>Niger<TD>Atlantic 0cear<TD>2600<TD>4180

</TR>

<TR>

<TD>Zambezi<TD>Indian 0cear<TD>1700<TD>2740

</TR>

</TABLE>

</B0DY>

</HTML>

hei ght wi dth

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

Compatibility / / / ✓

Example

Use The Evaluator (Chapter 13 in the JavaScript Bible) to adjust the w id th of the dem onstrator table. Begin by increasing the w id th to the fu ll w id th of the page:

document.getElementById("myTable").width = "100%"

To restore the table to its minim um w idth, assign a v e ry small value to the property:

document.getElementById("myTable").width = 50

If you have IE4+, you can perform sim ilar experiments w ith the hei ght p ro p e rty of the table.

rows

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

Compatibility / / / /

Example

Use The Evaluator to examine the num ber of rows in the dem onstrator table.

Enter the follow ing statement into the to p text box:

document. get ElementById("myTable") . rows.1ength

In contrast, notice how the rows p ro p e rty sees only the rows w ith in the demon­

s tra to r table’s TBODY element:

document. get ElementById("myTboCy") . rows.1ength

TABLE.rows

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

rul es

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

Compatibility / / / ✓

Example

Listing 27-5 presents a page that cycles through all possible settings fo r the

rul es property. The rul es p roperty value is displayed in the table’s caption. When you run this script, notice the nice border display fo r this table’s com bination of COLGROUP and table row segment elements. Figure 11-1 shows the IE/Windows rendition for the groups type of table rules. Early versions of NN6 may not render the altered table correctly, and scripted changes w on’t appear on the page.

Listing 27-5: Cycling Through Table rules Property Values

<HTML>

<HEAD>

<TITLE>TABLE.rules Property</TITLE>

<SCRIPT LANGUAGE“ "JavaScript">

var timeoutlD

var rulesValues = ["all", "cols", "groups” , "none", "rows"]

function rotateBorder(i) {

document.getElementByldi"myTABLE").rules = rulesValues[i]

document.getElementByldi"myCAPTION").i nnerHTML = rulesValues[i]

i = (++1 == rulesValues.lergth) ? 0 : i

timeoutlD = setTimeout("rotateBorder(" + i + ")", 2000) )

function stopRotateO ( clearTimeoutitimeout ID)

document.getElementByldi"myTABLE").rules = "all"

document.getElementByldi"myCAPTION").innerHTML = "all"

)

</SCRIPT>

</HEAD>

<B0DY>

<H1>TABLE.rules Property</Hl>

<HR>

<F0RM NAME="controls">

<FIELDSET>

<LEGEND>Cycle Table Rule Visibility</LEGEND>

<TABLE WIDTH="100%" CELLSPACING=20XTR>

<TD><INPUT TYPE="button" VALUE=”Cyc1 e" onCl1ck="rotateBorder(0)"></TD>

< T D X I N P U T TYPE=”button" VALUE="Stop” onClick="stopRotate()"X/TD>

</TR>

</TABLE>

</FIE LDS ET>

</TABLE>

</FIE LDS ET>

</F0RM>

TABLE.rules

Chapter 11 ♦ Table and List Objects (Chapter 27) 3 8 9

<HR>

<TABLE ID="myTABLE" CELLPADDING=5 B0RDER=3 ALIGN="center">

<CAPTION ID="myCAPTION">Default</CAPTI0N>

<C0LGR0UP SPAN=1>

<C0LGR0UP SPAN=3>

<THEAD ID=''myTHEAD">

<TR>

<TH>Ri ver<TH>Outf1ow<TH>Miles<TH>Ki1ometers

</TR>

</THEAD>

<TB0DY>

<TR>

<TD>Nile<TD>Mediterranean<TD>4160<TD>6700

</TR>

<TR>

<TD>Congo<TD>Atlanti c 0cear<TD>2900<TD>4670

</TR>

<TR>

<TD>Niger<TD>Atlantic 0cear<TD>2600<TD>4180

</TR>

<TR>

<TD>Zambezi <TD>Indi an 0cear<TD>1700<TD>2740

</TR>

</TABLE>

</B0DY>

</HTML>

3 TABLE.rules P rope rty - M icrosoft In te rn e t E xplorer

F ile E d it V ie w Favorites Too ls Help E H

T ■* . J I 3 Í i t a j d

1 U ù o k f OfWOfd S lo p R e fre s h H om e S c o rc h F a v o rite s H is to ry lé - 3S .

E d il

TABLE.rules Property

Cycle Table Rule Visibility

[C y c l^ J Stop 1

Done

groups

River Outflow M iles Kilometers

Nile M editerr anean 41 6 0 6700 Congo Atlantic O cean 2900 46 7 0 N iger Atlantic O cean 2600 4180 Zambezi Indian O cean 1700 2740

g j My Computer

Figure 11-1: The TABLE.rules property set to "groups"

TABLE.rules

tBodi es

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

Compatibility / / / ✓

3 9 0 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Example

Use The Evaluator (Chapter 13 in the JavaScript Bible) to access the t Bodies array and reveal the num ber of rows in the one TBODY segment of the demonstra­

to r table. Enter the follow ing statement into the to p text box:

document.get ElementById("myTable").tBodies[0].rows.1ength

Methods

moveRow( sourceRowIndex, destina1 7 onRowIndex)

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

Compatibility ✓ ✓

Example

If you want to sh ift the bottom row of a table to the top, you can use the shortcut reference to the last item ’s index value (- 1 ) for the firs t parameter:

var mnvedRow = document..al 1 .soitieTable.mnveRowt-1, 0)

TBODY, TFOOT, and THEAD Element Objects

Properties

vAli gn

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

Compatibility / / / /

Example

Use The Evaluator (Chapter 13 in the JavaScript Bible) to m odify the vertical align­

ment of the content of the TBODY element in the dem onstrator table. Enter the fol­

lowing statement in the top text box to shift the content to the bottom of the cells:

document.get ElementById("myTBoCy").vAli gn = "bottom”

TBODY.vAlign

Chapter 11 ♦ Table and List Objects (Chapter 27) 3 9 1

Notice tha t the cells of the THEAD element are untouched by the action imposed on the TBODY element.

COL and COLGROUP Element Objects

Properties

span

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

Compatibility / / / /

Example

The follow ing statement assigns a s p a n o f 3 t o a newly created COLGROUP element stored in the variable col GroupA:

colGroupA.span = 3

TR Element Object

Properties

cel 1 s

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

Compatibility / / / /

Example

Use The Evaluator (Chapter 13 in the JavaScript Bible) to retrieve the num ber of TD elements in the second row of the dem onstrator table. Enter the follow ing state­

ment into the top text box (W3C DOM syntax shown here):

document.getElementById("myTable").rows[l].cel 1s .1ength

hei ght

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

Compatibility / / ✓

TR.height

3 9 2 JavaScript Examples Bible: The Essential Companion to JavaScript Bible

Example

Use The Evaluator (Chapter 13 in the JavaScript Bible ) in IE4+ to expand the height of the second row of the dem onstrator table. Enter the following statement into the top text box:

document.all.myTable.rows[l],height = 300

If you attem pt to set the value ve ry low, the rendered height goes no smaller than the default height.

rowlndex

secti onRowIndex

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

Compatibility y s y y

Example

Use The Evaluator (Chapter 13 in the JavaScript Bible) to explore the rowl ndex and secti on Rowlndex p roperty values for the second physical row in the demon­

stra to r table. Enter each of the follow ing statements in to the top text box (W3C DOM syntax shown here):

document.get ElementById("myTable").rows[l].rowlndex document.get El ementById("myTable").rows[l].sect!onRowIndex

The result of the firs t statement is 1 because the second row is the second row of the entire table. But the secti onRowIndex p ro p e rty returns 0 because this row is the firs t row of the TBODY element in this particula r table.

TD and TH Element Objects

Properties

cel 1 Index

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

Compatibility / / / ✓

Example

You can rew rite the cell addition p o rtion of Listing 27-2 (in Chapter 27 in the JavaScript Bible) to utilize the cel 1 Index property. The process entails m odifying the insertTabl e R o w ( ) function so th a t it uses a d o . . .whi 1 e construction to keep adding cells to match the number of data slots. The function looks like the follow ing (changes shown in boldface):

TD.celllndex

Chapter 11 ♦ Table and List Objects (Chapter 27) 3 9 3

function insertTableRow(form, where) ( var now = new Date()

var nowData = [now.getHourst), now.getMinutes(), now.getSeconds(), now.getMi11iseconds()]

clearBGColors() var newCell

var newRow = theTableBody.insertRow(where) var i = 0

do {

newCell = newRow.insertCell (i) newCell.innerHTML = nowData[i++]

newCell.style.backgroundCol or = "salmon"

} while (newCell.cellIndex < nowData.length) updateRowCounters(form)

}

This version is merely for dem onstration purposes and is not as efficient as the sequence shown in Listing 27-2. But the cell I n d e x p ro p e rty version can give you some im plem entation ideas for the property. It also shows how dynamic the prop­

e rty is, even for brand new cells.

col Span rowSpan

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

Compatibility / / / /

Example

Use The Evaluator (Chapter 13 in the JavaScript Bible) to witness how m odifying either of these properties in an existing table can destroy the table. Enter the fol­

lowing statement into the top text box:

document.getElementById("myTable").rows[l].cel 1 s [0].col Span = 3

Now th a t the firs t cell of the second row occupies the space of three columns, the browser has no choice but to shift the tw o other defined cells for tha t row out beyond the original boundary of the table. Experiment w ith the r o w S p a n p ro pe rty the same way. To restore the original settings, assign 1 to each property.

hei ght wi dth

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

Compatibility / / / /

TD.height

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

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

(631 trang)