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

Học JavaScript qua ví dụ part 33 potx

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

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

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 12
Dung lượng 1,49 MB

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

Nội dung

If a function contains a setTimeout or setInterval method that in short intervals keeps invoking the function, the result can give the effect of continuous motion such as a scrolling pa

Trang 1

10.1.3 Creating Timed Events

Timer Methods. The window object provides two methods that act like an alarm

clock so that you can time when you want certain things to happen in your program:

E X P L A N A T I O N

1 A new window object is created If the resizable option is turned off, the user will

not be able to maximize the window A maximized window cannot be moved with

the moveTo() method.

2 The moveTo() method determines the position where the window will be moved

The arguments 0,0 represent the x,y coordinates (column,row) in pixels

3 The new window will be put into focus, meaning it will be at the top of the

win-dow hierarchy, in front of all the other winwin-dows

4 The parent window is the original window we started in It is moved to

coordi-nates 215 × 0 pixels

5 The parent (original) window is resized to 400 × 400 pixels

6 This is the start of a simple HTML form It creates a simple input device called a

button on the screen

7 This is the onClick event handler When the user presses the button, the event is

triggered and a function called directions(), will be called The new window is

moved to the top left corner and put into focus See Figure 10.18

Figure 10.18 After moving, focusing, and resizing both the new window and the

parent window: Output from Example 10.9.

Trang 2

setTimeout() and setInterval() (see Table 10.8) The setTimeout() method evaluates an

expression after a specified amount of time and quits The setInterval() method

automat-ically reschedules the execution of an expression at set intervals, continuing to repeat

until the program ends or the setInterval is cancelled

Both methods have the same syntax, two arguments: a quoted expression or function

reference, and the time in milliseconds to delay execution of the expression (A minute

contains 60,000 milliseconds, so 30 seconds would be 30,000 milliseconds.) Because

JavaScript sees time in terms of milliseconds, Table 10.9 gives you a little conversion

table to help determine the time in milliseconds

If a function contains a setTimeout() or setInterval() method that in short intervals

keeps invoking the function, the result can give the effect of continuous motion such as

a scrolling panorama or message, or even animation.3 Often, timers are used to scroll

messages in the title or status bars or in containers within a window such as a div or

textbox You must decide what is tasteful on your Web page and what is annoying, but

that aside, we use setTimeout() and clearTimeout() methods for scheduling something to

happen in the future For a detailed explanation of how JavaScript internally handles the

timers, see http://www.howtocreate.co.uk/tutorials/JavaScript/timers.

Table 10.8 Timers

Timing Methods What They Do

setTimeout() Invokes a function or evaluates an expression or a function when the

number of milliseconds has passed.

setInterval() Invokes a function or evaluates an expression or a function at set

intervals in milliseconds.

Table 10.9 Basic Units of Time

Unit of Time Milliseconds

3 For an example of a timer to create animation, see Chapter 15, “The W3C DOM and JavaScript.”

Trang 3

The setTimeout() and setInterval() methods are methods of the window object They

take two parameters:

1 The statements to execute: expressions in quotes or function references

2 The time in milliseconds to wait before the statements are executed

Which of the two timer functions should you use? It depends on what you are trying

to do If the function being called needs different parameters on each call or the content

of the function itself decides whether or not to call itself again, then you would use

set-Timeout() but if the function just needs to be called at regular intervals, then the

setInt-erval() function would produce simpler and faster results

You can cancel a timeout or interval by calling the clearTimeout() or clearInterval()

method by passing it a reference to the return value of setTimeout() or setInterval().

F O RM A T

var timeout = setTimeout("expression", delaytime);

var timeout= setInterval("expression", intervaltime);

E X A M P L E

var timeout = setTimeout("timer()", 15000); // In 15 seconds call the

// function "timer()"

var timeout = setTimeout(timer,15000); //Use function reference

var timerId = setInterval("scroller()", 500); // Every 5 seconds

// call "scroller()"

var timerId = setInterval(scroller, 500); //Use function reference

To clear the timed event use the clearTimeout() or clearInterval() methods:

clearTimeout(timeout);

clearInterval(timerID);

E X A M P L E 1 0 1 0

<html>

<head><title>The setTimeout method</title>

<script type="text/javascript">

1 function changeStatusBar(){

2 window.status = "See me now before I disappear!";

3 timeout =setTimeout("window.status=''", 6000);

// alert(timeout); This value differs in Mozilla and IE

}

</script>

</head>

<body><div align="center">

<font face="arial" size="3" color="blue">

The timeout is set for 6 seconds.

Trang 4

<br />

4 <img src="alarm.jpg" border=2>

<p>

Watch the status bar

<br />

5 <form>

<input type="button"

value="click here"

6 onClick="changeStatusBar();">

</form>

</font>

</div>

</body>

</html>

E X P L A N A T I O N

1 A JavaScript function, called changeStatusBar(), is defined Its purpose is to print

a message in the status bar of the window for six seconds

2 A string value is assigned to the status property of the window The string “See me

now before I disappear!” will appear in the status bar at the bottom of the window.

3 The setTimeout() method is a window method After six seconds, the status bar

will be set to an empty string Once the setTimeout() completes, it doesn’t

auto-matically start up again as setInterval() does.

4 This is an image of a clock that displays on the screen, just for decoration

5 An HTML form starts here The user will see a button, with the text “click here,”

on the button

6 When the user presses the button, the onClick event handler is triggered, causing

the function changeStatusBar() to be invoked See Figure 10.19.

Figure 10.19 Click the button and watch the status bar.

E X A M P L E 1 0 1 0 (C O N T I N U E D)

Trang 5

Some might find meddling with the status bar annoying In fact, JavaScript could be

enabled, but the ability to change the status bar might have been disabled For Firefox,

take the following steps to enable or disable the window’s features (see Figure 10.20):

1 Click Tools → Options

2 When the Options dialog box appears, click Content

3 Check Enable JavaScript if it is not already checked, and then click Advanced

4 The Advanced JavaScript Settings dialog box appears From here, you can

enable or disable features as desired

5 When done, click OK in the dialog boxes to close them

In the next example, a timer is used to create a scrolling message in both the title and

status bars of the window This is done by calling a function every 3 seconds that will

use JavaScript’s substring function to change the value in a string of text Removing the

first character of a string and then appending that value to the end of the same string,

all done repeatedly in rapid succession, gives the appearance of the text in motion This

example will be expanded in Chapter 15 to put the scrolling message in a <div>

con-tainer within the document

Figure 10.20 Enable/Disable window and status bar options with Firefox.

Trang 6

E X A M P L E 1 0 1 1

<html>

<! This script is a modification of a free script found at

the JavaScript source.

Author: Asif Nasir (Asifnasir@yahoo.com) >

<head>

<script type="text/javascript">

1 var today = new Date();

2 var year=today.getFullYear();

3 var future = new Date("December 25, " + year);

4 var diff = future.getTime() - today.getTime();

// Number of milliseconds

5 var days =Math.floor(diff / (1000 * 60 * 60 * 24 ));

// Convert to days

"Only " + days + " shopping days left until Christmas!";

7 function scroller(){

8 str = str.substring(1, str.length) + str.substring(0,1);

11 setTimeout(scroller, 300); // Set the timer

}

</script>

</head>

12 <body onload = "scroller()">

<b>

<font color="green" size="4">

Get Dizzy Watch the title bar and the status bar!!

<br />

<image src="christmasscene.bmp">

</font>

</body>

</html>

E X P L A N A T I O N

1 The Date() constructor creates an instance of a new Date object, called today.

2 The getFullYear() method returns the current year in four digits.

3 Another Date object is created with the date “December 25, 2010” assigned to the

variable, called future, assuming the current year is 2010.

4 The difference in milliseconds between the future time and the current time is

as-signed to the variable called diff.

5 The milliseconds of time are converted into days, and the result is rounded down

by the Math object’s floor() method.

6 The string variable, “Only (number of days goes here) shopping days left until

Christ-mas!”, is assigned to str.

Continues

Trang 7

7 A function called scroller() is defined

8 This looks kind of tricky, but here’s what’s happening The substr() method

ex-tracts everything between the first character and the rest of the string substr(1,

str.length), resulting in “nly 19 shopping days left until Christmas!” Next, another

subtsr(0,1) method extracts the first character from the string, the “O” The “O” is

added onto the end of the new string, resulting in “nly 19 shopping days left until

Christmas!O” and after 3 seconds the scroll() function will be called again Then

the string will become “ly 19 shopping days left until Christmas!On”, and then “19

shopping days left until Christmas!Onl” and so on Because the substr() method is

being called so rapidly, the effect is a scrolling banner

9 The new string, str, created by the two substr() methods will appear in the

docu-ment’s title bar Every time the function is called (i.e., every 3 seconds), the new

string will appear, giving a scrolling effect

10 The new string will also appear in the status bar of the window

11 The timer is set here within the scroller() function The first argument is a

refer-ence to a function that will be called, in this case, scroller, and the second

argu-ment is when it will be called, in this case, in 300 milliseconds or 3 seconds

(300/1000) Because the scroller() function calls itself within the timer, it is

recur-sive and will continue to call itself every 3 seconds until the program ends The

display is shown in Figure 10.21

E X A M P L E 1 0 1 2

<html>

<head><title><Timeout></title>

<script type="text/javascript">

var today = new Date();

var year=today.getFullYear();

var future = new Date("December 25,"+ year);

var diff = future.getTime() - today.getTime();

// Number of milliseconds var days =Math.floor(diff / (1000 * 60 * 60 * 24 ));

// Convert to days var str=

"Only " + days + " shopping days left until Christmas! ";

1 function startup(){

}

str = str.substring(1, str.length) + str.substring(0,1);

document.title=str;

window.status=str;

}

</script>

</head>

E X P L A N A T I O N (C O N T I N U E D)

Trang 8

The scrollTo() Method. This JavaScript method scrolls the content of a window to a

specified x/y coordinate pixel position This method is only useful where there are areas of

the document not viewable within the current viewable area of the window If you open

up another window, you might want to scroll to a particular place in the window based on

the user’s selection from a menu in the main window, or you might want to use scrolling

4 <body onLoad = "startup()">

<h3>

Get Dizzy Watch the title bar and the status bar!!

</h3>

<image src="christmasscene.bmp">

</body>

</html>

E X P L A N A T I O N

1 This is the same program as Example 10.11 using the setInterval() method for

set-ting a timer The function called startup() contains the code to start the scrolling.

2 The setInterval() method is a window method and is executed and calls scroller() at

intervals of 500 milliseconds (.5 seconds), and will continue to do so until the

win-dow is exited or the clearInterval() method is called In Example 10.11 we used

set-Timeout() instead of setInterval().

3 This is the scroller() function that creates the text in both the title bar and the

sta-tus bar It is executed at 5 second intervals

4 When the page has finished loading, the onLoad event handler will call startup().

Figure 10.21 The string “Only 19 shopping days left until Christmas!” scrolls

continuously in the title bar and in the status bar How annoying!

E X A M P L E 1 0 1 2 (C O N T I N U E D)

Trang 9

to produce an animated effect For example, if you have a large image that is too big to

view in the new window, you can set up scrolling so that you start at the left side of the

image and slowly move to a specified position at the right side and then back again, giving

a panoramic effect Scrolling might have different behavior on different browsers.4

The scrollTo() method takes two arguments, the horizontal and vertical pixel

coordi-nates to represent the window position, where 0,0 would scroll to the left top corner of

the window, and position 0,350 would scroll down 350 pixels from the starting position

at the top left corner, and 350,0 would scroll to the right 350 pixels from the starting

position, and so on

4 There might be browser compatibility issues with scrolling; for example, Example 10.13 works fine on a

Mozilla browser, but does not work on Internet Explorer because the image is scaled to fit the window no

matter what size it is For this example to work in IE, go to Tools → Internet Options → Advanced →

F O RM A T

window_object.scrollTo(horizontal_pixel_position,vertical_pixel_position);

E X A M P L E

parent.window.scrollTo(0,350);

E X A M P L E 1 0 1 3

<html>

<head><title>Scrolling through Autumn</title>

<script type="text/javascript">

1 winObj=window.open("fallscene.gif","mysscene",

"width=350,height=292,resizable=no"); // Create the new

// window with an // image.

2 winObj.moveTo(0, 0);

5 var ImgWidth=1096;

8 function startScroll(){

9 if (pixelpos <= (ImgWidth - 350)){

// Check that scrolling is still within the // boundaries of the window.

11 winObj.scrollTo(pixelpos,0); // Go to that position

// in the new window

} }

Trang 10

13 function scrollAgain(){

pixelpos = 0; // Reset the horizontal pixel position to 0

14 startScroll(); // Start scrolling again

} function stopHere(){

15 clearTimeout(timeout); // Stop the clock to stop scrolling

} function closeWindow(){

}

</script>

</head>

<body bgColor="lightgreen">

<font face="arial" size=4 >

<b><br />

<div align="center">

A Window into an Autumn Day

<form>

17 <input type="button"

value="Start scrolling"

onClick="startScroll();">

<input type="button"

value="Stop scrolling"

onClick="stopHere();">

<input type="button"

value="Start over"

onClick="scrollAgain();">

</form></font>

<font size=-1>

<p>When you are ready to close the window, click here<br />

18 <a href="JavaScript:closeWindow()">Close the window</a>

</font>

</body>

</html>

E X P L A N A T I O N

1 A new window object is created It will contain a gif image of a fall scene.

2 The new window object is moved up to the top left corner of the browser

(coordi-nates 0,0)

3 The focus() method puts the window on top of all other opened windows.

4 The initial pixel position that will be used for scrolling is set to 0

5 The variable ImgWidth is assigned 1096, which will be used to represent the size

of the image in pixels

6 Each time the image moves to the right, it will be moved 2 pixels in intervals of

.02 seconds

Continues

E X A M P L E 1 0 1 3 (C O N T I N U E D)

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