Beginning JavaScript Third Edition phần 8 ppt

79 320 0
Beginning JavaScript Third Edition phần 8 ppt

Đ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

width: 24px; border: 1px solid #316AC5; background-color: #C1D2EE; padding: 2px; cursor: pointer; } You’ve already seen the first three properties; they were used in the toolbar-button class. Next, a blue border one pixel in width is added to the element, and the background color is changed to a light blue. The padding is decreased to two pixels. You do this because padding and borders add extra height and width to the HTML element. Take a look at Figure 13-15, which illustrates this concept. Figure 13-15 This is a side-by-side comparison of the toolbar-button and toolbar-button-hover classes. The toolbar-button class is 24 pixels in height and width plus three pixels of padding per side. That makes toolbar-button 30 pixels in height and width. The toolbar-button-hover class starts with the same 24 pixels in height and width. You then add a one-pixel border, which adds two pixels to the height and width. Then you add two pixels of padding on each side, which makes toolbar-button-hover 30 pixels in height and width, just like toolbar- button . If you used three pixels of padding instead of two in toolbar-button-hover, the button would grow in size when the mouse pointer hovered over it, as Figure 13-16 shows. Padding <div/> <div/> Border Both elements 30 pixels in height and width Padding 530 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 530 Figure 13-16 Let’s take a second and look at these two rules. Notice that each has three properties with the same val- ues ( display, height, and width). You can take these properties out and write a new rule for all <span/> elements inside the toolbar. .toolbar span { display: inline-block; height: 24px; width: 24px; } You can now slim down the toolbar-button and toolbar-button-hover classes: .toolbar-button { padding: 3px; } .toolbar-button-hover { border: 1px solid #316AC5; background-color: #C1D2EE; padding: 2px; cursor: pointer; } By making this change, you can easily add style that is shared by both states. The last property we’ll discuss for the button is the cursor property. The mouse cursor (or pointer) is an important user interface component. It can tell the user when something is going on in the background or let him know when he can highlight text. It also changes to a hand when he moves the cursor over a link, letting him know that something will happen when he clicks it. Padding <div/> <div/> Border 32px30px Padding 531 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 531 As stated earlier, you want the user to understand what the toolbar is and what it does. By using the cursor property and setting it to pointer, you show the user a hand when he moves his mouse over a button. This offers the suggestion “Hey you! You can click me!” Styling the Icons The last style rule you need to write is one for the icons. These are simple <img/> elements with a CSS class name of toolbar-icon. .toolbar-icon { height: 24px; width: 24px; } By assigning height and width, you can constrain the image to a certain size. This will make sure that the icons look uniform. Storing Button Information You need some way to store the button information. In this script, you’ll use a multi-dimensional array to contain information for specific buttons. Let’s start with the first array. Let’s call it myToolbar. var myToolbar = new Array(); Each element in this array, myToolbar[x], will also be declared as an array. Each of these inner arrays will hold information for a particular button. You start this process with the array element of index 0. myToolbar[0] = new Array(); Now you can use the elements of this array, namely myToolbar[0][0] and myToolbar[0][1], to hold information about the first button. That information will be the image location for the icon and the page (or JavaScript code) to load when the button is clicked. So you see that the following code holds the loca- tion of the icon: myToolbar[0][0] = “img/green.gif”; The next line holds the web location, or JavaScript code, to load. myToolbar[0][1] = “javascript: alert(‘You Clicked the Green Button!’)”; Each button follows this pattern of defining a new Array object and inserting it in the first dimension. Then you make the second dimension of the array hold the icon information and the link or JavaScript code to load. myToolbar[0] = new Array(); myToolbar[0][0] = “img/green.gif”; myToolbar[0][1] = “javascript: alert(‘You Clicked the Green Button!’)”; myToolbar[1] = new Array(); 532 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 532 myToolbar[1][0] = “img/blue.gif”; myToolbar[1][1] = “javascript: alert(‘You Clicked the Blue Button!’)”; myToolbar[2] = new Array(); myToolbar[2][0] = “img/red.gif”; myToolbar[2][1] = “http://www.wrox.com”; Building the Toolbar You need a function to build the toolbar and populate it with buttons. Let’s write a function called createToolbar() that will do that for you. It needs to accept two arguments: the first one is the name of your toolbar, and the second is your multi-dimensional array containing the button information. You know how the HTML should be structured, so let’s get started. The first step is to dynamically create the <div/> element for the toolbar. function createToolbar(sName, aItems) { var toolbar = document.createElement(“div”); toolbar.id = sName; toolbar.className = “toolbar”; //more code here document.body.appendChild(toolbar); } In this code you create the <div/> element with the createElement() method and use the toolbar’s name, specified by the first argument, as its id attribute. You then assign its CSS class, toolbar, and append it to the document with the appendChild() method. You now have an empty toolbar, so you need to use the myToolbar array to populate it with buttons. You’ll do this with a for loop. function createToolbar(sName, aButtons) { var toolbar = document.createElement(“div”); toolbar.id = sName; toolbar.className = “toolbar”; for (var i = 0; i < aButtons.length; i++) { var thisButton = aButtons[i]; var button = document.createElement(“span”); var icon = document.createElement(“img”); //more code here } document.body.appendChild(toolbar); } 533 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 533 Inside the loop, you get the element of the array that corresponds to this button and assign it to thisButton. This enables you to easily access the button’s information. Then you create the required <span/> and <img/> elements. The button variable references the <span/> element, and the icon vari- able references the <img/> element. Next, add the href attribute to button with the setAttribute() method. The value of this attribute is contained in the thisButton[1] element of the thisButton array. Also set the CSS class. function createToolbar(sName, aButtons) { var toolbar = document.createElement(“div”); toolbar.id = sName; toolbar.className = “toolbar”; for (var i = 0; i < aButtons.length; i++) { var thisButton = aButtons [i]; var button = document.createElement(“div”); var icon = document.createElement(“img”); button.setAttribute(“href”, thisButton[1]); button.className = “toolbar-button”; icon.src = thisButton[0]; icon.className = “toolbar-icon”; button.appendChild(icon); toolbar.appendChild(button); } document.body.appendChild(toolbar); } This code also sets the src and className properties for the icon. You then append icon to button and add the button to the toolbar. With this code, the toolbar is created and populated with buttons, but it currently has no functionality. Remember, you want hover effects, and you want something to happen when a button is clicked. Handling User Interaction User interaction is an important part of DHTML; you usually want your HTML to react to something a user does, and the toolbar is no exception. As already mentioned, there are three areas of user interaction you want to handle: ❑ When the user moves her mouse pointer over a button ❑ When the user moves her mouse pointer off a button ❑ When the user clicks a button You’ll write one function to handle these events: button_mouseHandler(). 534 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 534 The button_mouseHandler() Function Using one function to handle the three mouse events is a time- and code-saving measure, especially in the case of this DHTML script. The function begins with its definition and two variables: function button_mouseHandler() { var eType = event.type; var eSrc = event.srcElement; //more code here } This DHTML script is quite similar to the image rollover scripts you wrote in the previous chapter. Here, you’re concerned only with the element that the event was fired upon (the source element) and the event type that called the event handler. The next step is to write the code for the mouseover event. function button_mouseHandler() { var eType = event.type; var eSrc = event.srcElement; if (eType == “mouseover”) { eSrc.className = “toolbar-button-hover”; } //more code here } This code checks to see if the event type is a mouseover event, and, if so, it changes the source element’s className property to toolbar-button-hover. Now it’s time to handle the mouseout event. When the mouse pointer leaves the button, the desired effect is to return the previously highlighted button to its original state. Therefore, the following code changes the className property of the source element (of the mouseout event) back to toolbar- button . function button_mouseHandler() { var eType = event.type; var eSrc = event.srcElement; if (eType == “mouseover”) { eSrc.className = “toolbar-button-hover”; } else if (eType == “mouseout”) { eSrc.className = “toolbar-button”; } //more code here } 535 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 535 Now things are beginning to take shape. When the mouse pointer moves over the button, its style changes to give a highlight effect, and the mouse pointer leaving the button returns it to its original state. Now you need to write the code to handle the click event, and the following code does this: function button_mouseHandler() { var eType = event.type; var eSrc = event.srcElement; //more code here if (eType == “mouseover”) { eSrc.className = “toolbar-button-hover”; } else if (eType == “mouseout”) { eSrc.className = “toolbar-button”; } else if (eType == “click”) { eSrc.className = “toolbar-button”; window.location.href = eSrc.getAttribute(“href”); } } The code handling the click event does two things. First, it returns the clicked button’s className property back to toolbar-button, and second, it navigates to the desired web page, or executes JavaScript code. But alas, all is not well. If you were to run this code, you would notice a few weird things happening. Buttons would highlight and unhighlight at strange times, the icons would grow to the size of the but- tons, and you’d see some very strange results if you clicked on a button when the mouse pointer was over an icon (the browser would navigate to the URL specified in the <img/> element’s src property). These behaviors may seem weird, but they are normal. As the mouse pointer moves over the <img/> element, it is no longer over the <span/> element (the button). Therefore, the mouseout event fires as the mouse leaves the <span/> and enters the <img/>. A simple solution to this problem is to check the source element’s tagName property, and, if it’s IMG, to access the image’s parent node: the <span/> element that represents the button. function button_mouseHandler() { var eType = event.type; var eSrc = event.srcElement; if (eSrc.tagName == “IMG”) { eSrc = eSrc.parentNode; } if (eType == “mouseover”) 536 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 536 { eSrc.className = “toolbar-button-hover”; } else if (eType == “mouseout”) { eSrc.className = “toolbar-button”; } else if (eType == “click”) { eSrc.className = “toolbar-button”; window.location.href = eSrc.getAttribute(“href”); } } Now the eSrc variable will always reference the <span/> element, making the button behave as you would expect it to. Finishing createToolbar() With the mouse event handler written, you can assign it to handle the appropriate events. Do this in createToolbar(). function createToolbar(sName, aButtons) { var toolbar = document.createElement(“div”); toolbar.id = sName; toolbar.className = “toolbar”; for (var i = 0; i < aButtons.length; i++) { var thisButton = aButtons[i]; var button = document.createElement(“span”); var icon = document.createElement(“img”); button.setAttribute(“href”, thisButton[1]); button.className = “toolbar-button”; button.onclick = button_mouseHandler; button.onmouseover = button_mouseHandler; button.onmouseout = button_mouseHandler; icon.src = thisButton[0]; icon.className = “toolbar-icon”; button.appendChild(icon); toolbar.appendChild(button); } document.body.appendChild(toolbar); } Now the code for the toolbar is complete. You have the toolbar, you populated it with buttons, and you added interactivity for those buttons. Now you need only to call createToolbar(). 537 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 537 Finishing Up Creating a toolbar is easy; however, there is one caveat you must consider. Since you generate the HTML elements dynamically and append them to document.body, you must create the toolbar while the docu- ment is loading, or after the document is loaded. If you attempt to load the toolbar at any other time, you’ll get errors in your page. In this exercise, you’ll use the onload event handler to create the toolbar after the document is loaded. Following is the complete source code for the toolbar DHTML script. Open the text editor of your choice and type the following: <!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”> <html xmlns=”http://www.w3.org/1999/xhtml”> <head> <title>IE Toolbar</title> <style type=”text/css”> .toolbar { background-color: #E4E2D5; padding: 2px; } .toolbar span { display: inline-block; height: 24px; width: 24px; } .toolbar-button { padding: 3px; } .toolbar-button-hover { border: 1px solid #316AC5; background-color: #C1D2EE; padding: 2px; cursor: pointer; } .toolbar-icon { height: 24px; width: 24px; } </style> <script type=”text/javascript”> function button_mouseHandler() { var eType = event.type; 538 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 538 var eSrc = event.srcElement; if (eSrc.tagName == “IMG”) { eSrc = eSrc.parentNode; } if (eType == “mouseover”) { eSrc.className = “toolbar-button-hover”; } else if (eType == “mouseout”) { eSrc.className = “toolbar-button”; } else if (eType == “click”) { eSrc.className = “toolbar-button”; window.location.href = eSrc.getAttribute(“href”); } } function createToolbar(sName, aButtons) { var toolbar = document.createElement(“div”); toolbar.id = sName; toolbar.className = “toolbar”; for (var i = 0; i < aButtons.length; i++) { var thisButton = aButtons[i]; var button = document.createElement(“span”); var icon = document.createElement(“img”); button.setAttribute(“href”, thisButton[1]); button.className = “toolbar-button”; button.onclick = button_mouseHandler; button.onmouseover = button_mouseHandler; button.onmouseout = button_mouseHandler; icon.src = thisButton[0]; icon.className = “toolbar-icon”; button.appendChild(icon); toolbar.appendChild(button); } document.body.appendChild(toolbar); } var myToolbar = new Array(); myToolbar[0] = new Array(); myToolbar[0][0] = “img/green.gif”; 539 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 539 [...]... XML is case-sensitive An element’s closing tag should exactly match its corresponding opening tag As you already know, the first line is the XML declaration, telling the XML parser that you’re using version 1.0 and the ISO -88 59-1 (Latin-1/West European) character set Next comes the root element, This element is descriptive of... declaration In this case the document conforms to the 1.0 specification of XML and uses the ISO -88 59-1 (Latin-1/West European) character set The next line describes the start tag of the root element of the document In this example, it’s saying “This document contains information on my dogs.” 554 Chapter 14: JavaScript and XML The next line opens the element, a child of the root element This... Here are some data fields to include: ❑ Name ❑ Age ❑ Breed ❑ Full blood ❑ Coat color Using these data fields, it’s possible to create the document’s structure 557 Chapter 14: JavaScript and XML What’s listed here is the... have no closing tag (like and ) So when you open a tag, you need to close it when it contains the data that you want it to Some data go here 552 Chapter 14: JavaScript and XML This example shows a simple XML document The first line contains the XML declaration This tells the application that is going to use this XML document... shows the data to use: Data Fields Dog 1 Dog 2 Dog 3 Name Morgan Molly Casey Age 10 months 8 years 6 years Breed Labrador Retriever Labrador Retriever Pomeranian Full Blood Yes Yes Yes Color Chocolate Yellow Brown Once again, open any plain-text editor, and create this XML document: ... a portion of it would look like: (rows removed for demonstration) ]> 562 Chapter 14: JavaScript and XML Either way you go, an XML parser that can validate... do so It is called Internet Explorer Tools for Validating XML and Viewing XSLT Output and can be found at www microsoft.com/downloads/details aspx?FamilyID=d23c1d2c-1571-4d61-bda8-adf9f 684 9df9&DisplayLang=en 564 Chapter 14: JavaScript and XML Figure 14-3 Here is something else: Look at the XML file in the browser (see Figure 14-1), and you’ll see several red dashes next to some opening tags Clicking... tells which version of XML the document uses The declaration also states the character encoding used in the document In this case the document conforms to the 1.0 specification of XML and uses the ISO -88 59-1 (Latin-1/West European) character set XML declarations have no closing tag After the declaration, you see a couple of tags enclosing some text The first tag is the opening tag for the myElement... incorrectly nested elements XML requires properly nested elements; they cannot overlap as they can in HTML For example, the following XML document is not well formed: Morgan Molly This XML is almost well formed; however, the second element’s closing tag comes after the closing tag This is an example... subdirectories, and so on An XML document is very similar You start with the root element and build the document from there For example, look at the following XML document: Morgan Molly The first element, , is the root element of the document From here, two elements called are added You could even go . 24px; } </style> <script type=”text /javascript > function button_mouseHandler() { var eType = event.type; 5 38 Chapter 13: Dynamic HTML in Modern Browsers 16_051511 ch13.qxp 4/13/07 6:23 PM Page 5 38 var eSrc = event.srcElement; if. hold the icon information and the link or JavaScript code to load. myToolbar[0] = new Array(); myToolbar[0][0] = “img/green.gif”; myToolbar[0][1] = javascript: alert(‘You Clicked the Green Button!’)”; myToolbar[1]. icon: myToolbar[0][0] = “img/green.gif”; The next line holds the web location, or JavaScript code, to load. myToolbar[0][1] = javascript: alert(‘You Clicked the Green Button!’)”; Each button follows

Ngày đăng: 09/08/2014, 14:21

Từ khóa liên quan

Mục lục

  • Beginning JavaScript, Third Edition

    • Chapter 13: Dynamic HTML in Modern Browsers

      • DHTML Example: The Toolbar in Firefox and Opera

      • Creating Cross-Browser DHTML

      • Summary

      • Exercise Questions

        • Question 1

        • Question 2

        • Chapter 14: JavaScript and XML

          • What Can XML Do for Me?

          • The Basics of XML

            • Understanding XML Syntax

            • Creating an XML Document

              • Document Type Definition

              • Creating the First DTD File

              • Bring on the Data

              • Altering the Look of XML

                • Style Sheets and XML

                • Extensible Stylesheet Language

                • Manipulating XML with JavaScript

                  • Retrieving an XML File in IE

                  • Determining When the XML File Has Loaded

                  • Retrieving an XML File in Firefox and Opera

                  • Determining When the File is Loaded

                  • Cross-Browser XML File Retrieval

                  • Displaying a Daily Message

                  • Summary

                  • Exercise Questions

                    • Question 1

Tài liệu cùng người dùng

Tài liệu liên quan