Thư viện tri thức trực tuyến
Kho tài liệu với 50,000+ tài liệu học thuật
© 2023 Siêu thị PDF - Kho tài liệu học thuật hàng đầu Việt Nam

THE BOOK OF JAVASCRIPT, 2ND EDITION phần 6 doc
Nội dung xem thử
Mô tả chi tiết
250 Chapter 13
The word true inside the cloneNode() method means that you want to
clone the node and all its children. In this case it would be the table and all
the contents of the table. If for some reason you didn’t want to make a copy
of the children, you’d put false there.
Once you’ve made your changes, you can replace the original table
with the new one using the replaceNode() method. Like insertBefore() and
removeChild(), this method is called by the parent of the nodes to be replaced.
Given the myTable and cloneTable variables defined above, you could do this:
var tableParent = myTable.parentNode;
tableParent.replaceChild(cloneTable, myTable);
Manipulating a Page Using the DOM
As mentioned earlier, you could do most of the things described in this
section with creative use of innerHTML. However, sometimes dealing with the
complex strings needed to get innerHTML to be what you want can be difficult.
In these cases, the DOM techniques are very helpful. When we get to the
chapters on Ajax, you’ll see even more applications of the DOM manipulation techniques.
Fancy Event Handling
Dynamic web pages call for dynamic reactions to user actions. We’ve discussed
how to write JavaScript that reacts when users click links, buttons, and form
elements. Now it’s time to learn about more complicated event handling:
how to accurately read the keyboard and the mouse.
The event Object
Whenever an event occurs, an event object is generated. The nature of this
object depends on the event which generated it. To access the event object,
simply pass the keyword event to whichever function is handling the event:
<a href = "#" onClick = "handleClick(event); return false; ">Click me!</a>.
The event object is most frequently accessed when you want to know
which key a user has pressed, or precisely where the mouse is.
Keyboard Events
There are two main keyboard event handlers, the functions of which are
pretty obvious: onKeyDown and onKeyUp. Triggering either of these event
handlers creates an event object that stores which key has been pressed
(or unpressed) and whether or not any special keys (ALT, CTRL, or SHIFT)
were pressed at the same time. The relevant properties of the event object
appear in Table 13-2.
Dynamic HTML 251
Figure 13-18 is short script that demonstrates how to use the event object
to determine which key a user has pressed while in a text input field.
<html><head><title>Demonstrating Keyboard Events</title>
<script type = "text/javascript">
<!-- hide me from older browsers
function displayEvent(evt) {
var type = evt.type;
X var code = evt.keyCode;
Y var theChar = String.fromCharCode(code);
var alt = evt.altKey;
var ctrl = evt.ctrlKey;
var shift = evt.shiftKey;
Z var displayString = "event type: " + type + "; key code: " + code +
", which is the character " + theChar +
"; ALT, CTRL, and SHIFT were: " +
alt + ", " + ctrl + ", and " + shift + "\n\n";
[ if ((code >= 65) && (code <= 90)) {
document.getElementById("showEvents").value += displayString;
}
}
// show me -->
</script>
</head>
<body>
<form>
Type here: <input type = "text"
\ onKeyDown = "displayEvent(event);" onKeyUp = "displayEvent(event);"><br>
See the events here: <textarea id = "showEvents" cols = "80" rows = "20">
</textarea>
</form>
</body>
</html>
Figure 13-18: Demonstrating keyboard events
Although the script in Figure 13-18 is simple, there are some subtleties.
First, whenever a user types anything while in the text field, the act of pressing
the key down creates one event, and the act of releasing the key creates
another event. These events are captured by the event handlers in \. In either
case, the displayEvent() function is called. This function creates variables for
each of the event’s properties, combines them into a string, and then puts the
Table 13-2: Properties for Keyboard Events
Property Type Description
altKey boolean True if the ALT key was down when this key was pressed
ctrlKey boolean True if the CTRL key was down when this key was pressed
shiftKey boolean True if the SHIFT key was down when this key was pressed
keyCode integer The Unicode decimal value for the key that was pressed; use
String.fromCharChode(keyCode) to convert this to a string
Type string The type of event—keyup or keydown, for example
252 Chapter 13
resulting string into the textarea with the id of showEvents. The most interesting
lines in this function are X, which gets a number representing the character
being pressed, and Y, which converts that number into an actual character.
After those lines are executed, Z creates a string representing what happened
in the event and [ puts that string in the text area if the key being pressed is
a letter (letters have character code numbers between 65 and 90).
Figure 13-19 shows what happens when a and then A are typed into the
text field. Notice that in both cases, the characterCode is 65, and the resulting
character is A. In order to determine whether the user has entered a capital
or lowercase letter, the shiftKey property of the event must be examined.
Figure 13-19: Typing a and A into the Figure 13-18 script
Mouse Events
Mouse events have their own properties. Unfortunately, some cross-browser
differences complicate accessing the position of the mouse and determining
which mouse button was clicked. Table 13-3 shows the properties of mouse
events, and it gives some details about how to deal with cross-browser
differences.
Table 13-3: Properties of Mouse Events
Property Description
button Equals 2 if it’s a right-click—otherwise, it depends on the browser
clientX Internet Explorer’s X position for the mouse
clientY Internet Explorer’s Y position for the mouse
pageX Most other browsers’ X position for the mouse
pageY Most other browsers’ Y position for the mouse
Dynamic HTML 253
As you can see from Table 13-3, all the properties of mouse events are
browser dependent. The button property, for example, describes which button
was clicked when an onMouseDown or onMouseUp event happened. However, the
meaning of the numbers provided by the button property depend on the
browser being used. In Internet Explorer, 1 means the left button was clicked,
2 means the right button, and 4 means the middle button. In most other
browsers, 0 means the left button, 1 means the middle button, and 2 means
the right button. Because 2 means the right button was clicked in both cases
and many people don’t have a middle button on their mouse, it is often safe to
see if the button property of the event was 2 and call it a left-click if it was not.
The position of the mouse is a bit trickier. Browsers other than Internet
Explorer generally use an event’s pageX and pageY properties to give a number
representing the X and Y positions (in pixels) of the event relative to the
top-left corner of the browser window. These two properties take into consideration scrolling a window. If a window is 10,000 pixels long and the user
has scrolled down to the very bottom, the pageY property will be around
10,000 at the bottom of the window. Internet Explorer, on the other hand,
uses properties named clientX and clientY. These properties do not take
scrolling into consideration, so to use them, you should add numbers representing how far down and to the left the browser has been scrolled. Those
numbers are available as document.body.scrollTop and document.body.scrollLeft.
Figure 13-20 presents a script that determines the X and Y positions of a
mouse and puts the results in a textarea.
<html><head><title>Checking Mouse Position</title>
<script type = "text/javascript">
<!-- hide me from older browsers
function displayEvent(evt)
{
var x = 0;
var y = 0;
X if (evt.pageX) {
Y x = evt.pageX;
y = evt.pageY;
Z } else if (evt.clientX) {
[ x = evt.clientX + document.body.scrollLeft;
y = evt.clientY + document.body.scrollTop;
}
\ document.getElementById("results").value += x + " " + y + "\n";
}
// show me -->
</script>
</head>
<body>
<div id = "box" style = "height:100px;width:100px;border:1px black solid;"
] onMouseMove = "displayEvent(event);"
^ onMouseOver = "document.getElementById('results').value='';"></div>
<form><textarea id = "results" cols = "80" rows = "20"></textarea></form>
</body>
</html>
Figure 13-20: Detecting the position of the mouse