|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Using Dynamic ImagesLong before the W3C DOM allowed JavaScript to change any part of a web page, a feature called dynamic images enabled you to swap one image for another with JavaScript. This technique is still supported by current browsers, and is still the most convenient (and compatible) way to work with images in JavaScript. Working with image ObjectsYou can change images dynamically by using the image object associated with each one. The traditional way to do this is with the document.images array. This array contains an item for each of the images defined on the page. In the object hierarchy, each image object is a child of the document object. With the W3C DOM, you can also assign an id attribute to an image within the <img> tag, and then use document.getElementById to find the object for that image. Each image object has the following properties:
For most purposes, the src attribute is the only one you'll use. The image object has no methods. It does have three event handlers you can use:
By the Way Although changing image sources works fine, you can also use the W3C DOM to completely remove or replace image objects, or insert new ones, just like any other object. Preloading ImagesYou can also create an independent image object. This enables you to specify an image that will be loaded and placed in the cache, but will not be displayed on the page. This might sound useless, but it's a great way to work with modem-speed connections. After you've preloaded an image, you can replace any of the images on the page with that imageand because it's already cached, the change happens instantly. Even on a fast connection, this avoids flickering and makes animation smoother. You can cache an image by creating a new image object, using the new keyword. Here's an example: Image2 = new Image(); Image2.src = "arrow1.gif"; By the Way You learned about the new keyword and its other uses for object-oriented programming in Hour 6, "Using Functions and Objects." |
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |