mozilla
Risultati di ricerca

    Esempi

    Questa pagina fornisce alcuni esempi estesi di sviluppo web e XML usando il DOM. Dove possibile, gli esempi usano API comuni, trick e pattern in Javascript per manipolare il documento.

    Esempio 1: altezza e larghezza

    L'esempio seguente mostra l'utilizzo delle proprietà height e width tra immagini di varie dimensioni:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    
    <html lang="en">
    
    <head>
    <title>width/height example</title>
    <script type="text/javascript">
    function init()
    {
      var arrImages = new Array(3);
      arrImages[0] = document.getElementById("image1");
      arrImages[1] = document.getElementById("image2");
      arrImages[2] = document.getElementById("image3");
      var objOutput = document.getElementById("output");
      var strHtml = "<ul>";
      for (var i = 0; i < arrImages.length; i++)
        strHtml += "<li>image" + (i+1) + 
                ": height=" + arrImages[i].height + 
                ", width=" + arrImages[i].width + 
                ", style.height=" + arrImages[i].style.height + 
                ", style.width=" + arrImages[i].style.width + 
                "<\/li>";
      strHtml += "<\/ul>";
      objOutput.innerHTML = strHtml;
    }
    </script>
    </head>
    <body onload="init();">
    
    <p>Image 1: no height, width, or style 
        <img id="image1" src="http://www.mozilla.org/images/mozilla-banner.gif">
    </p>
    <p>Image 2: height="50", width="500", but no style 
        <img id="image2" src="http://www.mozilla.org/images/mozilla-banner.gif" 
             height="50" width="500">
    </p>
    <p>Image 3: no height, width, but style="height: 50px; width: 500px;"
        <img id="image3" src="http://www.mozilla.org/images/mozilla-banner.gif" 
             style="height: 50px; width: 500px;">
    </p>
    
    <div id="output"> </div>
    </body>
    </html>
    

    height and width are also properties of the OBJECT and APPLET elements.

    Esempio 2: Attributi dell'immagine

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    
    <html lang="en">
    
    <head>
    <title>Modifying an image border</title>
    <script type="text/javascript">
    function setBorderWidth(width) {
      document.getElementById("img1").style.borderWidth = width + "px";
    }
    </script>
    </head>
    
    <body>
    <p>
      <img id="img1" src="image1.gif" style="border: 5px solid green;" width="100"
    height="100" alt="border test">
    </p>
    
    <form name="FormName">
      <p><input type="button" value="Make border 20px-wide" 
    onclick="setBorderWidth(20);"> <input type="button" value="Make border 5px-wide" 
    onclick="setBorderWidth(5);"></p>
    </form>
    
    </body>
    </html>
    

    Esempio 3: Manipolare gli stili

    In this simple example, some basic style properties of an HTML paragraph element are accessed using the style object on the element and that object's CSS style properties, which can be retrieved and set from the DOM. In this case, you are manipulating the individual styles directly. In the next example (see Example 4), you can use stylesheets and their rules to change styles for whole documents.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    
    <html lang="en">
    
    <head>
    <title>Changing color and font-size example</title>
    <script type="text/javascript">
    function changeText() {
    	var p = document.getElementById("pid");
    	p.style.color = "blue"
    	p.style.fontSize = "18pt"
    }
    </script>
    </head>
    <body>
    <p id="pid" 
    onclick="window.location.href = 'http://www.cnn.com/';">linker</p>
    <form>
    <p><input value="rec" type="button" onclick="changeText();"></p>
    </form>
    </body>
    </html>
    

    Esempio 4: Usare l'oggetto Stylesheets

    The styleSheets property on the document object returns a list of the stylesheets that have been loaded on that document. You can access these stylesheets and their rules individually using the stylesheet, style, and CSSRule objects, as demonstrated in this example, which prints out all of the style rule selectors to the console.

    ss = document.styleSheets;
    for(i=0; i<ss.length; i++)
     {
     for(j=0; j<ss[0].cssRules.length; j++)
      {
      dump( ss[i].cssRules[j].style.selectorText + "\n" );
      }
     }
    

    For a document with a single stylesheet in which the following three rules are defined:

    BODY { background-color: darkblue; }
    P { font-face: Arial; font-size: 10pt; margin-left: .125in; }
    #lumpy { display: none; }
    

    This script outputs the following:

    BODY
    P
    #LUMPY
    

    Esempio 5: Propagazione di un evento

    This example demonstrates how events fire and are handled in the DOM in a very simple way. When the BODY of this HTML document loads, an event listener is registered with the top row of the TABLE. The event listener handles the event by executing the function stopEvent, which changes the value in the bottom cell of the table.

    However, stopEvent also calls an event object method, event.stopPropagation, which keeps the event from bubbling any further up into the DOM. Note that the table itself has an onclick event handler that ought to display a message when the table is clicked. But the stopEvent method has stopped propagation, and so after the data in the table is updated, the event phase is effectively ended, and an alert box is displayed to confirm this.

    <html>
    <head>
    <title>Event Propagation</title>
    
    <style type="text/css">
     #t-daddy { border: 1px solid red }
     #c1 { background-color: pink; }
    </style>
    
    <script type="text/javascript">
    
    function stopEvent(ev) {
      c2 = document.getElementById("c2");
      c2.innerHTML = "hello";
    
      // this ought to keep t-daddy from getting the click.
      ev.stopPropagation();
      alert("event propagation halted.");
    }
    
    function load() {
      elem = document.getElementById("tbl1");
      elem.addEventListener("click", stopEvent, false);
    }
    </script>
    </head>
    
    <body onload="load();">
    
    <table id="t-daddy" onclick="alert('hi');">
     <tr id="tbl1">
      <td id="c1">one</td>
     </tr>
     <tr>
      <td id="c2">two</td>
     </tr>
    </table>
    
    </body>
    </html>
    

    Esempio 6: il metodo getComputedStyle

    This example demonstrates how the window.getComputedStyle method can be used to get the styles of an element that are not set using the style attribute or with JavaScript (e.g., elt.style.backgroundColor="rgb(173, 216, 230)"). These latter types of styles can be retrieved with the more direct elt.style property, whose properties are listed in the DOM CSS Properties List.

    getComputedStyle() returns a ComputedCSSStyleDeclaration object, whose individual style properties can be referenced with this object's getPropertyValue() method, as the following example document shows.

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
    "http://www.w3.org/TR/html4/strict.dtd">
    
    <html lang="en">
    
    <head>
     <title>getComputedStyle example</title>
    
     <script type="text/javascript">
       function cStyles() 
      {
       var RefDiv = document.getElementById("d1");
    
       var txtHeight = document.getElementById("t1");
       var h_style = 
    document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("height");
       txtHeight.value = h_style;
    
       var txtWidth = document.getElementById("t2");
       var w_style = 
    document.defaultView.getComputedStyle(RefDiv, null).getPropertyValue("width");
       txtWidth.value = w_style;
    
       var txtBackgroundColor = document.getElementById("t3");
       var b_style = 
    document.defaultView.getComputedStyle(RefDiv,
    null).getPropertyValue("background-color");
       txtBackgroundColor.value = b_style;
      }
     </script>
    
     <style type="text/css">
       #d1 { margin-left: 10px; background-color: rgb(173, 216, 230); 
    height: 20px; max-width: 20px; }
     </style>
    
    </head>
    
    <body>
    
    <div id="d1">&nbsp;</div>
    
    <form action="">
    <p><button type="button" onclick="cStyles();">getComputedStyle</button>
      height<input id="t1" type="text" value="1">
      max-width<input id="t2" type="text" value="2">
      bg-color<input id="t3" type="text" value="3"></p>
    </form>
    
    </body>
    </html>
    

    Esempio 7: Visualizzare le costanti dell'oggetto Event

    This example shows how to use the DOM to create a table in which all of the constants in the event object and their values are displayed. It shows off several useful aspects of the DOM, including the Event.prototype property, which allows you to get to the properties of a particular object, a good pattern for iterating over the properties in that prototype, and the values of the constants themselves displayed in the table. Note that the middle range of these constants are the character codes that represent the actual keys pressed during the event (and fetchable with the charCode property). Load the following code as a web page to see the event object constants.

    <?xml version="1.0" ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd">
    <!--
     * ***** BEGIN LICENSE BLOCK *****
     * Version: NPL 1.1/GPL 2.0/LGPL 2.1
     *
     * The contents of this file are subject to the Netscape Public License
     * Version 1.1 (the "License"); you may not use this file except in
     * compliance with the License. You may obtain a copy of the License at
     * http://www.mozilla.org/NPL/
     *
     * Software distributed under the License is distributed on an "AS IS" basis,
     * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
     * for the specific language governing rights and limitations under the
     * License.
     *
     * Contributor(s):
     *   Alexander J. Vincent <jscript@pacbell.net>
     *
     * Alternatively, the contents of this file may be used under the terms of
     * either the GNU General Public License Version 2 or later (the "GPL"), or 
     * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
     * in which case the provisions of the GPL or the LGPL are applicable instead
     * of those above. If you wish to allow use of your version of this file only
     * under the terms of either the GPL or the LGPL, and not to allow others to
     * use your version of this file under the terms of the NPL, indicate your
     * decision by deleting the provisions above and replace them with the notice
     * and other provisions required by the GPL or the LGPL. If you do not delete
     * the provisions above, a recipient may use your version of this file under
     * the terms of any one of the NPL, the GPL or the LGPL.
     *
     * ***** END LICENSE BLOCK ***** * -->
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head><title></title>
    <script language="JavaScript" type="text/javascript">
    <!--
    function respond() {
    // creating a table 
        var table = document.createElement("table")
        table.setAttribute("border", "1")
        var tbody = document.createElement("tbody")
        var y = 0
        var tr = document.createElement("tr")
        var td = document.createElement("th")
    // reusing the same variable name in the loop
    // begin table heading information
        td.appendChild(document.createTextNode("Index"))
        tr.appendChild(td)
        td = document.createElement("th")
        td.appendChild(document.createTextNode("Property Name"))
        tr.appendChild(td)
        td = document.createElement("th")
        td.appendChild(document.createTextNode("Property Value"))
        tr.appendChild(td)
        tbody.appendChild(tr)
    // end table heading information
        for (property in Event.prototype) {
            if (property == property.toUpperCase()) {
    // adding a new row for each property of the event object
                tr = document.createElement("tr")
                td = document.createElement("td")
                td.appendChild(document.createTextNode(y))
    // which property number it happens to be
                tr.appendChild(td)
                y++
                td = document.createElement("td")
                var td_text = document.createTextNode(property)
    // the property name
                td.appendChild(td_text)
                tr.appendChild(td)
                td = document.createElement("td")
                var td_text = document.createTextNode(Event.prototype[property])
    // the property value
                td.appendChild(td_text)
                tr.appendChild(td)
                tbody.appendChild(tr)
                }
            }
        table.appendChild(tbody)
        document.body.appendChild(table)
        }
    //-->
    </script>
    </head>
    <body onload="respond()">
    <!-- Results after clicking on the button:
    The this object is myInput.
    Index    Property Name Property Value
    0        type          click
    1        target        [object HTMLInputElement]
    ...
    -->
    </body>
    </html>
    

    Etichette del documento e nomi di chi ha collaborato alla sua stesura

    Contributors to this page: jsx, Joey santiago, DaViD83, teoli
    Ultima modifica di: jsx,