Tải bản đầy đủ (.pdf) (10 trang)

Học JavaScript qua ví dụ part 44 pot

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.46 MB, 10 trang )

ptg
413
chapter
12
Working with Images
(and Links)
12.1 Introduction to Images
A picture is worth a thousand words. Whether it’s a slide show, banner, movie, or photo
album, the Web contains a huge collection of images. Any time you buy something
online, there is usually an image associated with the item, maybe a small image, and then
a bigger image if you want more detail. Whatever it is, a book, a house, a pair of shoes,
or a toy, we like to see it before we put it in our virtual shopping cart and pay the money.
Although the focus of this chapter is on JavaScript and images, hypertext links are so
closely intertwined with images and navigation, they are also discussed here.
Images can be links, clickable image maps, banners, marquees, billboards, or roll-
overs—you name it. With HTML, the images you load are static, and just sit on the page.
They cannot be changed without loading a brand new page, and loading a lot of images
takes time. JavaScript brings a new dimension to working with images. Instead of view-
ing a static image on the page, you can create dynamic images that can be changed on
the fly, adding animation and drama to your Web page. For example, you can create
effects such rollovers, slide shows, cycling banners, dynamic menus, and more. Just as
with forms, JavaScript has access to every image on you page. Before getting into the fun
of images, we will look at how JavaScript accesses them. In Chapter 13, “Handling
Events,” and Chapter 15, “The W3C DOM and JavaScript,” you utilize what you learn
here to see the full potential of image manipulation with JavaScript.
From the Library of WoweBook.Com
ptg
414 Chapter 12 • Working with Images (and Links)
12.1.1 HTML Review of Images
Before using images with JavaScript, the following section reviews the basics of using
images in a static Web page. Table 12.1 lists HTML image tags.


Table 12.1 HTML Image Tags
Tag Attributes Description
IMG Starting tag for loading an image.
ALIGN Floats the image either to the left or right side of the page, or aligns
the image with text in directions, texttop, top, middle, absmiddle,
bottom, or absbottom.
ALT Alternative text in case the image doesn’t appear.
BORDER The width in pixels of an image border.
HEIGHT Height of the image in pixels.
HSPACE Adds space, in pixels, to both the right and left sides of the image.
SRC Contains the URL, location of the image relative to the document root
of the Web page.
VSPACE Adds space, in pixels, to both the top and bottom of the image.
WIDTH Width of the image in pixels.
MAP Starting tag for an image map. Image maps link areas of an image with
a set of URLs. Clicking on an area of the map sends the user to that
page.
ID The name of the image map.
NAME Also the name of the image map.
AREA Defines the clickable areas of the image map.
ALT Describes what happens when the user clicks.
COORDS Determines the shape of a rectangle, circle, or polygon in x,y pixel
coordinates.
HREF The address of the page that will appear when the user clicks in a
particular area.
SHAPE Assigned a type, where type represents the shape of the area.
From the Library of WoweBook.Com
ptg
12.1 Introduction to Images 415
Using an Image in an HTML Web Page. Example 12.1 is an HTML file linked to

an image. In this example, we review the way inline images are created in a document.
EXAMPLE 12.1
<html>
<head><title>HTML Images</title></head>
<body bgcolor="lightblue">
1 <img src="baby.jpg" alt="baby" border=2 align="left"
2 hspace="10" width="220" height="250" />
3 <pre>
Father calls me William,
sister calls me Will,
Mother calls me Willie,
but the fellers call me Bill!
Mighty glad I ain't a girl
ruther be a boy,
Without them sashes, curls, an' things
that's worn by Fauntleroy!
Love to chawnk green apples
an' go swimmin' in the lake
Hate to take the castor-ile
they give for belly-ache!
Most all the time, the whole year round,
there ain't no flies on me,
But jest 'fore Christmas
I'm as good as I kin be!
</pre>
</body>
</html>
__________________________
Eugene Field, Jest ‘Fore Christmas,in Childcraft, Vol. 2, (Chicago:
Field Enterprises, Inc., 1949).

EXPLANATION
1 The image src attribute defines where the image is located. This image, baby.jpg,
is located where the HTML file called image.html is found, normally under the
document root of your browser. If the image can’t be loaded, the alt attribute spec-
ifies text that will appear in its place. The image will be aligned at the left side of
the page and will have a thin black border around it. There will be 10 pixels of
space on both the left and right sides of the image. This keeps the text from jam-
ming up too close to the picture.
2 The width and height attributes of the img tag allow you to specify the size of your
image in pixels. If you right-click on an image (Windows), a popup window will
appear where you can select Properties to obtain info about your image.
3 This is a <pre> tag that is followed by all the text that appears at the right side of
the image. See Figure 12.1.
From the Library of WoweBook.Com
ptg
416 Chapter 12 • Working with Images (and Links)
12.1.2 The JavaScript image Object
With the Legacy DOM, JavaScript provided the image object as a property of the docu-
ment object, giving you easy access to the images that have been loaded into a document.
Although you can use the W3C versions of the DOM, the Legacy DOM is supported by
all modern browsers and is commonly used when working with images. Just like the
form object, the image object corresponds to the HTML <img> tag and each image is
assigned to the images[] array
1
in the order in which the image appears within the doc-
ument. The first image would be represented as document.images[0], the next as docu-
ment.images[1], and so on (see Figure 12.2). As with forms, images can also be named
and given an id. The properties for the image object correspond to the HTML attributes
of the <img> tag, such as src, width, height, border, vspace, and hspace, and are shown in
Table 12.2.

2
It is possible to assign values to these properties to dynamically change the
size, shape, and border of the image. There are no common methods for the image object
unless you use the id attribute and methods such as getElementById() and getElements-
ByTagName() provided by the W3C DOM.
JavaScript also provides event handlers that are triggered when an image is loaded, a
mouse crosses the image, or when the user clicks on an image. Although we use event
handling in this chapter, Chapter 13 provides a more complete discussion.
Figure 12.1 Using images in an HTML page: Output from Example 12.1.
1. Implemented starting in JavaScript 1.1.
2. These properties are common to both Mozilla/Firefox and Internet Explorer. Internet Explorer, however,
supports many more than those listed here.
From the Library of WoweBook.Com
ptg
12.2 Reviewing Links 417
For preloading offscreen images, JavaScript provides an image constructor (see
Example 12.6). The constructor is used if you have large images that will take time to
download or images that are being replaced dynamically within the page. The images are
preloaded into memory (but not displayed) and available from the cache when the user
requests them, thus making the response time much faster (see Example 12.4).
12.2 Reviewing Links
Links are fundamental to the Web. They are primarily used to navigate you from page
to page. We have been using links in many examples so far. There are a number of ways
to execute JavaScript from a link such as navigating to another page, opening a link in
Figure 12.2 Document object and images.
Table 12.2 image Object Properties
Property HTML <img>
Attribute
Description
border border An integer value determining the width of an image border in pixels.

complete A Boolean value returning true if Navigator has finished
downloading the image.
height height An integer representing the height of the image in pixels.
hspace hspace An integer representing the horizontal space (pixels) around the
image.
lowsrc lowsrc Specifies an optional image to display for a low-resolution device.
name name A string containing the name of the image.
prototype Used to add user-specified properties to an image object.
src src A string containing the path and name of the image.
vspace vspace An integer representing the vertical space (pixels) around the image.
width width An integer representing the width of the image in pixels.
images[0] images[1] images[ ]
window
document
From the Library of WoweBook.Com
ptg
418 Chapter 12 • Working with Images (and Links)
a popup window, calling a function from a link, submitting a form from a link, and so
on. This chapter focuses on how links are used with images.
As you know, HTML hypertext links are usually created by assigning a Web address
or a file name to the HTML <a href> tag, for example:
<a href="">Go Home</a>
If a JavaScript function is assigned to the <a href> tag, when the user clicks the link,
the function will be executed (see Example 12.4).
<a href="JavaScript:greetings()"><big>Click here for salutations</big>
<a href="JavaScript: function_name(arguments);"> Do Something </a>
And you can use an event handler with a link (see Chapter 13):
<a href="newpage.htm" onClick="newwindow();return false">Click Here!</A>
<a href=JavaScript: onClick="return handler(arguments)" >
<A HREF="JavaScript:newwindow()" ><IMG SRC="mypic.jpg" border="0"></A>

12.2.1 The JavaScript links Object
Like the form object and image object, the link object is a property of the document
object and gives you access to the hypertext links that have been loaded into a document
(see Figure 12.3). It corresponds to the HTML <a href> tag. As each HTML form is a Java-
Script element of the forms[] array, and each image is assigned to the images[] array, so
each link is assigned to the links[] array in the order in which the link appears within
the document.
The first link would be represented as document.links[0]. The properties for the links
object are shown in Tables 12.3 and 12.4.
3
There are no common methods for the links
object.
Figure 12.3 Document object and links.
3. These properties are common to both Netscape and Internet Explorer. Internet Explorer, however, sup-
ports many more than are listed here.
links[0] links[1] links[ ]
window
document
From the Library of WoweBook.Com
ptg
12.2 Reviewing Links 419
A links object contains a URL, similar to the window’s location object, and shares the
same properties. A full URL takes the following form:
<protocol>//<host>[:<port>]/<pathname>[<hash>][<search>]
There are nine events that can be triggered by a link: onClick, onDblClick, onKey-
Down, onKeyPress, onKeyUp, onMouseDown, onMouseUp, onMouseOver, and onMouse-
Out. (For details, see Chapter 13.)
Table 12.3 Properties of the W3C links Object
Property What It Describes
charset Sets or returns the character encoding of the target URL.

disabled Sets or returns whether or not the target URL should be disabled.
href The entire URL.
hreflang Sets or returns the base language of the target URL.
id Sets or returns the id of a <link> element.
media Sets or returns on what device the document will be displayed.
name The name of the <link> element.
rel Sets or returns the relationship between the current document and the
target URL.
rev Sets or returns the relationship between the target URL and the current
document.
Table 12.4 Properties of the JavaScript links Object
Property What It Describes
hash The anchor part of the URL (if any).
host The hostname port part of the URL.
hostname The hostname part of the URL.
href The entire URL.
pathname The pathname part of the URL.
port The port part of the URL.
Continues
From the Library of WoweBook.Com
ptg
420 Chapter 12 • Working with Images (and Links)
protocol The protocol part of the URL, including the colon.
search The query part of the URL.
target The HTML target attribute of the link.
EXAMPLE 12.2
<html>
<title>Using Links </title></head>
<body>
<h2>Links and their Properties</h2>

<big>
1 <a href=" Script
tutorial">
Search for JavaScript Stuff</a>
<p>
2 <a href="?" >Go to google</a>
</p><p>
3 <a href="">Go to bing</a>
</p>
<script type = "text/javascript">
document.write("<br /><b>This document contains "
+document.links.length + " links.<br /></b>");
4 for (i = 0; i< document.links.length; i++){
5 document.write("<u>document.links["+i+"]:</u><br />");
5 document.write("<b>hostname:</b> "
+document.links[i].hostname +"<br />");
6 document.write("<b>href: </b>"
+document.links[i].href +"<br />");
7 document.write("<b>pathname:</b>"
+document.links[i].pathname +"<br />");
8 document.write("<b>port:</b> "
+document.links[i].port +"<br />");
9 document.write("<b>query string:</b> "
+document.links[i].search +"<br />");
10 document.write("<b>protocol:</b> "
+document.links[i].protocol +"<br /><br />");
}
</script>
</big>
</body>

</html>
Table 12.4 Properties of the JavaScript links Object (continued)
Property What It Describes
From the Library of WoweBook.Com
ptg
12.2 Reviewing Links 421
EXPLANATION
1 This link goes to the Yahoo! search engine’s main site and searches for the word
“JavaScript tutorial.” Note: The browser inserted a %20 for the space between
“JavaScript”and “tutorial”, an example of URL encoding.
2 This link goes to the Google search engine’s main site.
3 This link goes to the Bing search engine’s main site.
4 The size of the links[] array is determined by the length property. It displays the
number of links in the document.
5–10 The for loop is used to iterate through the links array and display some of its prop-
erties. The output is shown in Figures 12.4 and 12.5.
Figure 12.4 Viewing the properties of the links object.
From the Library of WoweBook.Com
ptg
422 Chapter 12 • Working with Images (and Links)
12.3 Working with Imagemaps
An imagemap is an image with clickable areas where each area is represented by a link,
also called a hotspot. An imagemap makes it possible to make one image link to several
pages depending on the area or pixel coordinate positions clicked by the user. A simple
example would be an image of the map of the United States. If the user clicks on Maine,
for example, then a link would navigate the user to another page with information about
that state, a closer image of the state, and so forth.
In the HTML page you simply specify the area of the image (hotspot) and the link
that will be associated with that part of the image. The most time-consuming and boring
part of this process is determining the coordinate positions for the hotspot. This can be

done manually or by an image mapping program. There are a number of programs on
the Web to help you (see Figure 12.6), and many are free. In fact, most HTML editors
have image mapping as a built-in function (see Figures 12.7 and 12.8).
Figure 12.5 After clicking on a hyperlink: Output from Example 12.2.
From the Library of WoweBook.Com

×