1. Trang chủ
  2. » Công Nghệ Thông Tin

JavaScript Bible, Gold Edition part 198 pdf

10 63 0
Tài liệu đã được kiểm tra trùng lặp

Đang tải... (xem toàn văn)

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 532,37 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Enter the following statement into the top text box: document.myIMG.protocol src Example In the following example Listing 22-4, you see a few applications of image objects.. As a bonus,

Trang 1

You can use The Evaluator to examine the protocolproperty of the image on the page Enter the following statement into the top text box:

document.myIMG.protocol

src

Example

In the following example (Listing 22-4), you see a few applications of image objects.

Of prime importance is a comparison of how precached and regular images feel to the user As a bonus, you see an example of how to set a timer to automatically change the images displayed in an image object This feature is a popular request among sites that display advertising banners.

As the page loads, a global variable is handed an array of image objects Entries of the array are assigned string names as index values (“desk1”, “desk2”, and so on) The intention is that these names ultimately will be used as addresses to the array entries Each image object in the array has a URL assigned to it, which precaches the image.

The page (see Figure 22-1) includes two IMG elements: one that displays noncached images and one that displays cached images Under each image is a SELECT ele-ment that you can use to select one of four possible image files for each eleele-ment The onChangeevent handler for each SELECT list invokes a different function to change the noncached (loadIndividual()) or cached (loadCached()) images Both of these functions take as their single parameter a reference to the form that contains the SELECT elements.

To cycle through images at five-second intervals, the checkTimer()function looks

to see if the timer check box is checked If so, the selectedIndexproperty of the cached image SELECT control is copied and incremented (or reset to zero if the index is at the maximum value) The SELECT element is adjusted, so you can now invoke the loadCached()function to read the currently selected item and set the image accordingly.

For some extra style points, the <BODY>tag includes an onUnloadevent handler that invokes the resetSelects()function This general-purpose function loops

Trang 2

through all forms on the page and all elements within each form For every SELECT

element, the selectedIndexproperty is reset to zero Thus, if a user reloads the

page, or returns to the page via the Back button, the images start in their original

sequence An onLoadevent handler makes sure that the images are in sync with the

SELECT choices and the checkTimer()function is invoked with a five-second delay.

Unless the timer check box is checked, however, the cached images don’t cycle.

Listing 22-4: A Scripted Image Object and Rotating Images

<HTML>

<HEAD>

<TITLE>Image Object</TITLE>

<SCRIPT LANGUAGE=”JavaScript”>

// global declaration for ‘desk’ images array

var imageDB

// pre-cache the ‘desk’ images

if (document.images) {

// list array index names for convenience

var deskImages = new Array(“desk1”, “desk2”, “desk3”, “desk4”)

// build image array and pre-cache them

imageDB = new Array(4)

for (var i = 0; i < imageDB.length ; i++) {

imageDB[deskImages[i]] = new Image(120,90)

imageDB[deskImages[i]].src = deskImages[i] + “.gif”

}

}

// change image of ‘individual’ image

function loadIndividual(form) {

if (document.images) {

var gifName =

form.individual.options[form.individual.selectedIndex].value

document.thumbnail1.src = gifName + “.gif”

}

}

// change image of ‘cached’ image

function loadCached(form) {

if (document.images) {

var gifIndex = form.cached.options[form.cached.selectedIndex].value

document.thumbnail2.src = imageDB[gifIndex].src

}

}

// if switched on, cycle ‘cached’ image to next in queue

function checkTimer() {

if (document.images && document.Timer.timerBox.checked) {

var gifIndex = document.selections.cached.selectedIndex

if (++gifIndex > imageDB.length - 1) {

gifIndex = 0

Continued

IMG.src

Trang 3

Listing 22-4: A Scripted Image Object and Rotating Images

} document.selections.cached.selectedIndex = gifIndex loadCached(document.selections)

var timeoutID = setTimeout(“checkTimer()”,5000) }

} // reset form controls to defaults on unload function resetSelects() {

for (var i = 0; i < document.forms.length; i++) { for (var j = 0; j < document.forms[i].elements.length; j++) {

if (document.forms[i].elements[j].type == “select-one”) { document.forms[i].elements[j].selectedIndex = 0 }

} } } // get things rolling function init() { loadIndividual(document.selections) loadCached(document.selections) setTimeout(“checkTimer()”,5000) }

</SCRIPT>

</HEAD>

<BODY onLoad=”init()” onUnload=”resetSelects ()”>

<H1>Image Object</H1>

<HR>

<CENTER>

<TABLE BORDER=3 CELLPADDING=3>

<TR><TH></TH><TH>Individually Loaded</TH><TH>Pre-cached</TH></TR>

<TR><TD ALIGN=RIGHT><B>Image:</B></TD>

<TD><IMG SRC=”cpu1.gif” NAME=”thumbnail1” HEIGHT=90 WIDTH=120></TD>

<TD><IMG SRC=”desk1.gif” NAME=”thumbnail2” HEIGHT=90 WIDTH=120></TD>

</TR>

<TR><TD ALIGN=RIGHT><B>Select image:</B></TD>

<FORM NAME=”selections”>

<TD>

<SELECT NAME=”individual” onChange=”loadIndividual(this.form)”>

<OPTION VALUE=”cpu1”>Wires

<OPTION VALUE=”cpu2”>Keyboard

<OPTION VALUE=”cpu3”>Desks

<OPTION VALUE=”cpu4”>Cables

</SELECT>

</TD>

<TD>

<SELECT NAME=”cached” onChange=”loadCached(this.form)”>

<OPTION VALUE=”desk1”>Bands

Trang 4

<OPTION VALUE=”desk2”>Clips

<OPTION VALUE=”desk3”>Lamp

<OPTION VALUE=”desk4”>Erasers

</SELECT></TD>

</FORM>

</TR></TABLE>

<FORM NAME=”Timer”>

<INPUT TYPE=”checkbox” NAME=”timerBox” onClick=”checkTimer()”>Auto-cycle through

pre-cached images

</FORM>

</CENTER>

</BODY>

</HTML>

Figure 22-1: The image object demonstration page (Images (c) Aris Multimedia

Entertainment, Inc 1994)

IMG.src

Trang 5

Example

See Listing 22-3 earlier in this chapter for an example of how you can use the start

property with a page that loads a movie clip into an IMG element object.

x y

Example

If you want to scroll the document so that the link is a few pixels below the top of the window, use a statement such as this:

window.scrollTo(document.images[0].x, (document.images[0].y - 3))

Event handlers onAbort

onError

Trang 6

Listing 22-5 includes an onAbortevent handler If the images already exist in the

cache, you must quit and relaunch the browser to try to stop the image from

load-ing In that example, I provide a reload option for the entire page How you handle

the exception depends a great deal on your page design Do your best to smooth

over any difficulties that users may encounter

onLoad

Example

Quit and restart your browser to get the most from Listing 22-5 As the document

first loads, the LOWSRC image file (the picture of pencil erasers) loads ahead of the

computer keyboard image When the erasers are loaded, the onLoadevent handler

writes “done” to the text field even though the main image is not loaded yet You

can experiment further by loading the arch image This image takes longer to load,

so the LOWSRC image (set on the fly, in this case) loads way ahead of it.

Listing 22-5: The Image onLoad Event Handler

<HTML>

<HEAD>

<SCRIPT LANGUAGE=”JavaScript”>

function loadIt(theImage,form) {

if (document.images) {

form.result.value = “”

document.images[0].lowsrc = “desk1.gif”

document.images[0].src = theImage

}

}

function checkLoad(form) {

if (document.images) {

form.result.value = document.images[0].complete

}

}

function signal() {

if(confirm(“You have stopped the image from loading Do you want to try

again?”)) {

Continued

IMG.onLoad

Trang 7

Listing 22-5 (continued)

location.reload() }

}

</SCRIPT>

</HEAD>

<BODY>

<IMG SRC=”cpu2.gif” LOWSRC=”desk4.gif” WIDTH=120 HEIGHT=90 onLoad=”if (document.forms[0].result) document.forms[0].result.value=’done’” onAbort=”signal()”>

<FORM>

<INPUT TYPE=”button” VALUE=”Load keyboard”

onClick=”loadIt(‘cpu2.gif’,this.form)”>

<INPUT TYPE=”button” VALUE=”Load arch”

onClick=”loadIt(‘arch.gif’,this.form)”><P>

<INPUT TYPE=”button” VALUE=”Is it loaded yet?” onClick=”checkLoad(this.form)”>

<INPUT TYPE=”text” NAME=”result”>

</FORM>

</BODY>

</HTML>

AREA Element Object

Properties coords shape

Example

See Listing 22-7 for a demonstration of the coordsand shapeproperties in the con-text of scripting MAP element objects.

Trang 8

MAP Element Object

Property

areas

Example

Listing 22-7 demonstrates how to use scripting to replace the AREA element objects

inside a MAP element The scenario is that the page loads with one image of a

com-puter keyboard This image is linked to the keyboardMapclient-side image map,

which specifies details for three hot spots on the image If you then switch the

image displayed in that IMG element, scripts change the useMapproperty of the

IMG element object to point to a second MAP that has specifications more suited to

the desk lamp in the second image Roll the mouse pointer atop the images, and

view the URLs associated with each area in the statusbar (for this example, the

URLs do not lead to other pages).

Another button on the page, however, invokes the makeAreas()function (not

working in IE5/Mac), which creates four new AREA element objects and (through

DOM-specific pathways) adds those new area specifications to the image If you roll

the mouse atop the image after the function executes, you can see that the URLs

now reflect those of the new areas Also note the addition of a fourth area.

Listing 22-7: Modifying AREA Elements on the Fly

<HTML>

<HEAD>

<TITLE>MAP Element Object</TITLE>

<SCRIPT LANGUAGE=”JavaScript”>

// generate area elements on the fly

function makeAreas() {

document.myIMG.src = “desk3.gif”

// build area element objects

var area1 = document.createElement(“AREA”)

area1.href = “Script-Made-Shade.html”

area1.shape = “polygon”

Continued

MAP.areas

Trang 9

Listing 22-7 (continued)

area1.coords = “52,28,108,35,119,29,119,8,63,0,52,28” var area2 = document.createElement(“AREA”)

area2.href = “Script-Made-Base.html”

area2.shape = “rect”

area2.coords = “75,65,117,87”

var area3 = document.createElement(“AREA”) area3.href = “Script-Made-Chain.html”

area3.shape = “polygon”

area3.coords = “68,51,73,51,69,32,68,51”

var area4 = document.createElement(“AREA”) area4.href = “Script-Made-Emptyness.html”

area4.shape = “rect”

area4.coords = “0,0,50,120”

// stuff new elements into MAP child nodes

if (document.all) { // works for IE4+

document.all.lampMap.areas.length = 0 document.all.lampMap.areas[0] = area1 document.all.lampMap.areas[1] = area2 document.all.lampMap.areas[2] = area3 document.all.lampMap.areas[3] = area4 } else if (document.getElementById) { // NN6 adheres to node model var mapObj = document.getElementById(“lamp_map”) while (mapObj.childNodes.length) {

mapObj.removeChild(mapObj.firstChild) }

mapObj.appendChild(area1) mapObj.appendChild(area2) mapObj.appendChild(area3) mapObj.appendChild(area4) // workaround NN6 display bug document.myIMG.style.display = “inline”

} function changeToKeyboard() { document.myIMG.src = “cpu2.gif”

document.myIMG.useMap = “#keyboardMap”

} function changeToLamp() { document.myIMG.src = “desk3.gif”

document.myIMG.useMap = “#lampMap”

}

</SCRIPT>

</HEAD>

<BODY>

<H1>MAP Element Object</H1>

Trang 10

<IMG NAME=”myIMG” SRC=”cpu2.gif” WIDTH=120 HEIGHT=90 USEMAP=”#keyboardMap”>

<FORM>

<P><INPUT TYPE=”button” VALUE=”Load Lamp Image” onClick=”changeToLamp()”>

<INPUT TYPE=”button” VALUE=”Write Map on the Fly” onClick=”makeAreas()”></P>

<P>

<INPUT TYPE=”button” VALUE=”Load Keyboard Image”

onClick=”changeToKeyboard()”></P>

</FORM>

<MAP NAME=”keyboardMap”>

<AREA HREF=”AlpaKeys.htm” SHAPE=”rect” COORDS=”0,0,26,42”>

<AREA HREF=”ArrowKeys.htm” SHAPE=”polygon”

COORDS=”48,89,57,77,69,82,77,70,89,78,84,89,48,89”>

<AREA HREF=”PageKeys.htm” SHAPE=”circle” COORDS=”104,51,14”>

</MAP>

<MAP NAME=”lampMap”>

<AREA HREF=”Shade.htm” SHAPE=”polygon”

COORDS=”52,28,108,35,119,29,119,8,63,0,52,28”>

<AREA HREF=”Base.htm” SHAPE=”rect” COORDS=”75,65,117,87”>

<AREA HREF=”Chain.htm” SHAPE=”polygon” COORDS=”68,51,73,51,69,32,68,51”>

</MAP>

</BODY>

</HTML>

Chapter 23 Examples

The following section contains examples from Chapter 23, “The Form and Related

Objects.”

FORM Object

Properties

action

FORM.action

Ngày đăng: 06/07/2014, 06:20