|
Free Open Book
Sams Teach Yourself JavaScript in 24 Hours |
Controlling Styles with JavaScriptThe new W3C DOM (Document Object Model) makes it easy for JavaScript applications to control the styles on a page. Whether or not you use style sheets, you can use JavaScript to modify the style of any element on a page. As you learned in Hour 4, "Working with the Document Object Model (DOM)," the DOM enables you to access the entire HTML document and all of its elements as scriptable objects. You can change any object's style by modifying its style object properties. The names and values of objects under the style object are the same as you've learned in this hour. For example, you can change an element's color by modifying its style.color attribute: element.style.color="blue"; Here, element represents the object for an element. There are many ways of finding an element's corresponding object, which you will learn about in detail in Hour 13. In the meantime, an easy way to find an element's object is to assign an identifier to it with the id attribute. The following statement creates an <h1> element with the identifier "head1": <h1 id = "head1">This is a heading</h1> Now that you've assigned an identifier, you can use the getElementById() method to find the DOM object for the element: element = document.getElementById("head1");
You can also use a shortcut to set styles and avoid the use of a variable by directly working with the getElementbyId() method: document.getElementById("head1").style.color="blue";
This statement combines the preceding examples by directly assigning the blue color style to the head1 element of the page. You'll use this technique to create a dynamic page in the following Try It Yourself section.
|
Main Menu |
| 500 Juegos Gratis | 500 Giochi Gratis | 500 Jeux Gratuits | 500 Jogos Gratis | 500 Kostenlose Spiele |