Đang chuẩn bị liên kết để tải về tài liệu:
Học JavaScript qua ví dụ part 47

Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ

Hiển thị ngẫu nhiên các hình ảnh và sự kiện onClick Bằng cách sử dụng phương pháp ngẫu nhiên () của đối tượng của toán học, đôi khi vui vẻ để tạo ra hình ảnh ngẫu nhiên từ danh sách các hình ảnh. Ví dụ 12,7 thể hiện như thế nào để thay đổi thuộc tính src của một đối tượng hình ảnh bằng cách sử dụng một số ngẫu nhiên như là các chỉ số của một phần tử trong một loạt hình ảnh. Tất cả các hình ảnh được cài đặt sẵn bằng cách sử dụng hình ảnh (). | 434 Chapter 12 Working with Images and Links EXPLANATION continued 8 When the mouse is moved away from the link the initial image baby1.jpg will reappear on the screen. 9 The initial external image called baby1.jpg is named willy and is aligned on the left side of the screen. The output is shown in Figure 12.13. Figure 12.13 Before the mouse rolls over the image left as the mouse hovers over the image middle and when the mouse moves away from the image right . 12.3.3 Randomly Displaying Images and the onClick Event By using the Math object s randomO method it is sometimes fun to randomly generate pictures from a list of images. Example 12.7 demonstrates how to change the src attribute of an image object by using a random number as the index of an element in an image array. All of the images are preloaded by using the ImageQ constructor greatly improving the time it takes to load the images. EXAMPLE 12.7 html head title Preloading Images title head script type text javascript 1 ImageHome new Array 3 2 for var i 0 i 3 i ImageHome i new Image 3 ImageHome 0 .src baby1.jpg ImageHome 1 .src baby2.jpg ImageHome 2 .src baby3.jpg 4 function myRandom 5 var n ImageHome.length - 1 6 var randnum Math.floor Math.random n 1 7 document.images display .src ImageHome randnum .src script From the Library of WoweBook.Com 12.3 Working with Imagemaps 435 EXAMPLE 12.7 continued head body bgcolor cornflowerblue center h2 nbsp nbsp This Is Baby William h2 8 img name display id display src baby.jpg border 5 width 200 height 250 p form 9 input type button value Click Here for Baby Picture 10 onClick myRandom form center body html EXPLANATION 1 The ArrayO constructor creates an array object to consist of three elements. This array will be used to hold three images. 2 The Image constructor will preload and cache three images and assign them to the array created in line 1. 3 The src property of the first element of the image array is assigned an image called baby1.jpg. Each array element is .