Resizing Text with JavaScript

2019-07-01 23:25发布

问题:

I have a problem with making two buttons in my HTML code increase or decrease text when I click on either button. I have what I think is the correct javascript code I just have a problem with the buttons working. Any help with this issue is appreciated.

HTML

<!DOCTYPE html>
<html>

   <head>
      <meta charset="UTF-8" />
      <title>Twin Life Magazine</title>
      <script src="modernizr-1.5.js"></script>
      <script src="fontsizer.js"></script>
      <link href="tlm.css" rel="stylesheet" type="text/css" />


   </head>

   <body onload="startup()">

  <section id="main">
     <header>
        <img src="twinlife.png" alt="The Chamberlain Civic Center" />
        <div>Search
           <input type="search" name="sbox" id="sbox" />
        </div>
     </header>

     <nav class="horizontal">
        <ul>
           <li><a href="#">News</a></li>
           <li><a href="#">Features</a></li>
           <li><a href="#">Articles</a></li>
           <li><a href="#">Twins Store</a></li>
           <li><a href="#">Current Issue</a></li>
           <li><a href="#">Archive</a></li>
           <li><a href="#">Submissions</a></li>
           <li><a href="#">Contact Us</a></li>
        </ul>
     </nav>

     <nav class="vertical">
        <h1>Current Issue</h1>
        <ul>
           <h2>Notes</h2>
           <li class="newgroup"><a href="#">From the Editor's Desk</a></li>
           <li><a href="#">Twin Life Staff</a></li>
           <li><a href="#">Event Calendar</a></li>
           <li><a href="#">Mailbag</a></li>
           <h2>Articles</h2>
           <li class="newgroup"><a href="#">Multiple Births on the Rise</a></li>
           <li><a href="#">Chicago Convention: A Great Event</a></li>
           <li><a href="#">Twins in Adolescence</a></li>
           <li><a href="#">Twins and Talking</a></li>
           <li><a href="#">Switching Roles</a></li>
           <h2>Features</h2>
           <li class="newgroup"><a href="#">Twin Tips</a></li>
           <li><a href="#">Photos of the Month</a></li>
           <li><a href="#">Recipe Corner</a></li>
           <li><a href="#">Consumer Report</a></li>
           <li><a href="#">Swap Meet</a></li>
           <li class="newgroup"><a href="#">Reader Survey</a></li>
        </ul>
     </nav>

     <article>
        <hgroup>
           <div id="fontbuttons">
              <input type="image" id="fontdown" alt="-" src="fontdown.png" button value="-0.1" />
              <input type="image" id="fontup" alt="+" src="fontup.png" button value="0.1" />
              window.onload=function(){startup();};
           </div>

           <h1>Twins and Talking</h1>
           <h2>by Peter Kuhlman, M.D., Ph.D.</h2>

        </hgroup>
        <figure>
           <img src="kuhlman.png" alt="" />
        </figure>

        <p>Communication occurs long before speech. Babies communicate 
           with their parents through crying, laughter, smiling and 
           pointing. The attentive parent quickly becomes attuned to 
           this "non-speech" communication. Usually in the second year of 
           life, babies will begin to add single words to these acts 
           of expression. A baby will point to a cup and say, "drink."
           The names "Mama" and "Dada" are among the first out of a
           baby's mouth.
        </p>
        <p>As the child gets older, he or she will add new words to 
           these expressions and will begin to use words in 
           combination: "get drink me." The parents provide visual
           and audio feedback to the child, encouraging the development 
           of speech. Through a process called echoing, parents 
           will naturally repeat what their child says, providing an 
           important confirmation that what the child has said has 
           been heard and understood.
        </p>
        <p>With twins, the situation may be slightly different. 
           Often parents cannot provide the one-to-one feedback that 
           single children routinely enjoy. It may be that the one 
           providing most of the feedback is the other twin!
        </p>
        <p>While the other twin is usually a very attentive and 
           eager audience, he or she cannot provide the type of 
           feedback needed for language development. Twins
           cannot correct each other's mistakes in the use of words 
           or grammar. Moreover, by communicating with each other, 
           twins are necessarily decreasing the amount of communication 
           with adults and older children. In some cases, twins become 
           such good audiences for each other, they lose interest
           in communicating with their parents!
        </p>
        <p>In rare cases, this one-to-one communication can progress 
           to the point at which a shared language is created. 
           The twins will come up with their own words, and in some 
           cases, their own grammatical structures. The languages
           are unintelligible to anyone else but the twins. These cases 
           are very rare, even though they are well publicized. 
           The twin's secret language will usually disappear by age 
           4 or 5, as they become more adept at using their
           parent's language.
        </p>
        <p>What can you do to help your twins in acquiring 
           language? The most important thing you can do is pay 
           individual attention to each child. Easier said than
           done! Provide feedback to each child as he or she gropes 
           with language. If you are feeding your twins, talk to one 
           child as the other is eating. Then, when the first child 
           is eating, switch to the second. When changing
           diapers, use the one-on-one time (one hopes) to further 
           provide the audio clues needed for learning language.
        </p>
        <p>As with everything that is twin-related, language 
           acquisition requires some extra work on the part of the 
           parents; but again with twin-related activities,
           the extra work is paid off in extra fun.
        </p>
     </article>


     <footer>
        Twin Life Magazine: Issue 189; &copy; 2015 (US)
        <span>
           <a href="#">About</a>
           <a href="#">Terms</a>
           <a href="#">Help</a>
        </span>
     </footer>

  </section>

  </body>

  </html>

JavaScript

function startup() {
   var fontButtons = document.getElementsByClassName("fontsizer");
   var i;
   alert(fontButtons.length);
   for (i = 0; i < fontButtons.length; i++) {
      fontbuttons[i].onclick = function(){resizeText(this);};
   }

   function resizeText(ObjectButton) {
      var fontChange;
      fontChange = parseFloat(objectButton.value);

      if (document.body.style.fontSize == "") {
      document.body.fontSize = "1.0em";
    }

  var currentFontSize;
  alert("changed");
  currentFontSize = parseFloat(document.body.style.fontSize);
  currentFontSize = currentFontSize + fontChange;
  document.body.style.fontSize = "currentFontSize+em"
   }
}

回答1:

First add fontsizer class name to the buttons:

<input class="fontsizer" type="image" id="fontdown" alt="-" src="fontdown.png" button value="-0.1" />
<input class="fontsizer" type="image" id="fontup" alt="+" src="fontup.png" button value="0.1" />

Then:

function startup()
{
    var fontButtons = document.getElementsByClassName ("fontsizer");
    alert (fontButtons.length);
    for (i = 0; i < fontButtons.length; i++)
    {
        fontButtons[i].onclick = function()
        {
            resizeText(this);
        };
    }

    function resizeText (objectButton)
    {
        var fontChange = parseFloat (objectButton.value);

        if (document.body.style.fontSize == "")
        {
            document.body.style.fontSize = "1.0em";
        }

        var size = document.body.style.fontSize;
        var currentFontSize = parseFloat(size);
        currentFontSize += fontChange;
        document.body.style.fontSize = currentFontSize + "em"
    }
}

Note that variables names are case sensitive, so ObjectButton and objectButton are not the same, also don't put variables inside strings their values wont be used, also there's no need to declare variables first and then initialize them, you can do that simultaneously.

JSFiddle



回答2:

You have several errors in both HTML and JS. First you are looking for "document.getElementsByClassName("fontsizer")"

But the buttons/inputs dont have fontsizer as a class.

Error:

<input type="image" class="fontsizer" id="fontdown" alt="-" src="fontdown.png" button value="-0.1" />
<input type="image" class="fontsizer" id="fontup" alt="+" src="fontup.png" button value="0.1" />

Fix:

<input type="image" class="fontsizer" id="fontdown" alt="-" src="fontdown.png" button value="-0.1" />
              <input type="image" class="fontsizer" id="fontup" alt="+" src="fontup.png" button value="0.1" />

Then is The JS: JavaScript is case-sensitive so there is a difference between ObjectButton and objectButton or fontbuttons and fontButtons

This:

currentFontSize = parseFloat(document.body.style.fontSize);

Most likely will return NaN, so you can't make any arithmetic operations.

Another mistake:

document.body.style.fontSize = "currentFontSize+em";

currentFontSize+ must be outside the quotes ( " " )

FIX:

function startup() {
    var fontButtons = document.getElementsByClassName("fontsizer");

    for (var i = 0; i < fontButtons.length ; i++) {
        fontButtons[i].addEventListener("click", function(){
            resizeText(this);
        });
    }

    function resizeText(ObjectButton) {
        var fontChange = parseFloat(ObjectButton.value);

        var currentFontSize = parseFloat(document.body.style.fontSize);
        currentFontSize = (isNaN(currentFontSize)) ? 1 : currentFontSize;
        currentFontSize += fontChange;

        document.body.style.fontSize = currentFontSize + "em";
    }
}


回答3:

I've made a couple of modifications to your code in order to make it work, I also included comments with explanations in each section, but feel free to ask again if something remains unclear.

function startup() {
  // I've modified the selector to match the HTML here, feel free to change this
  var fontButtons = document.querySelectorAll("#fontbuttons input");
  var i;

  for (i = 0; i < fontButtons.length; i++) {
    // You can assign the resizeText function directly, and access the button
    // with 'this' (see below)
    fontButtons[i].onclick = resizeText;
  }

  function resizeText(e) {
    var fontChange;
    // Here you can access to the input with 'this'
    fontChange = parseFloat(this.value);

    if (document.body.style.fontSize == "") {
      document.body.style.fontSize = "1.0em";
    }

    var currentFontSize;
    currentFontSize = parseFloat(document.body.style.fontSize);
    currentFontSize = currentFontSize + fontChange;
    document.body.style.fontSize = currentFontSize + "em";
    // Let's prevent the default click behavior
    e.preventDefault();
  }
}
<section id="main">
     <header>
        <img src="twinlife.png" alt="The Chamberlain Civic Center" />
        <div>Search
           <input type="search" name="sbox" id="sbox" />
        </div>
     </header>

     <nav class="horizontal">
        <ul>
           <li><a href="#">News</a></li>
           <li><a href="#">Features</a></li>
           <li><a href="#">Articles</a></li>
           <li><a href="#">Twins Store</a></li>
           <li><a href="#">Current Issue</a></li>
           <li><a href="#">Archive</a></li>
           <li><a href="#">Submissions</a></li>
           <li><a href="#">Contact Us</a></li>
        </ul>
     </nav>

     <nav class="vertical">
        <h1>Current Issue</h1>
        <ul>
           <h2>Notes</h2>
           <li class="newgroup"><a href="#">From the Editor's Desk</a></li>
           <li><a href="#">Twin Life Staff</a></li>
           <li><a href="#">Event Calendar</a></li>
           <li><a href="#">Mailbag</a></li>
           <h2>Articles</h2>
           <li class="newgroup"><a href="#">Multiple Births on the Rise</a></li>
           <li><a href="#">Chicago Convention: A Great Event</a></li>
           <li><a href="#">Twins in Adolescence</a></li>
           <li><a href="#">Twins and Talking</a></li>
           <li><a href="#">Switching Roles</a></li>
           <h2>Features</h2>
           <li class="newgroup"><a href="#">Twin Tips</a></li>
           <li><a href="#">Photos of the Month</a></li>
           <li><a href="#">Recipe Corner</a></li>
           <li><a href="#">Consumer Report</a></li>
           <li><a href="#">Swap Meet</a></li>
           <li class="newgroup"><a href="#">Reader Survey</a></li>
        </ul>
     </nav>

     <article>
        <hgroup>
           <div id="fontbuttons">
              <input type="image" id="fontdown" alt="-" src="fontdown.png" button value="-0.1" />
              <input type="image" id="fontup" alt="+" src="fontup.png" button value="0.1" />
              <script>window.onload=function(){startup();};</script>
           </div>

           <h1>Twins and Talking</h1>
           <h2>by Peter Kuhlman, M.D., Ph.D.</h2>

        </hgroup>
        <figure>
           <img src="kuhlman.png" alt="" />
        </figure>

        <p>Communication occurs long before speech. Babies communicate 
           with their parents through crying, laughter, smiling and 
           pointing. The attentive parent quickly becomes attuned to 
           this "non-speech" communication. Usually in the second year of 
           life, babies will begin to add single words to these acts 
           of expression. A baby will point to a cup and say, "drink."
           The names "Mama" and "Dada" are among the first out of a
           baby's mouth.
        </p>
        <p>As the child gets older, he or she will add new words to 
           these expressions and will begin to use words in 
           combination: "get drink me." The parents provide visual
           and audio feedback to the child, encouraging the development 
           of speech. Through a process called echoing, parents 
           will naturally repeat what their child says, providing an 
           important confirmation that what the child has said has 
           been heard and understood.
        </p>
        <p>With twins, the situation may be slightly different. 
           Often parents cannot provide the one-to-one feedback that 
           single children routinely enjoy. It may be that the one 
           providing most of the feedback is the other twin!
        </p>
        <p>While the other twin is usually a very attentive and 
           eager audience, he or she cannot provide the type of 
           feedback needed for language development. Twins
           cannot correct each other's mistakes in the use of words 
           or grammar. Moreover, by communicating with each other, 
           twins are necessarily decreasing the amount of communication 
           with adults and older children. In some cases, twins become 
           such good audiences for each other, they lose interest
           in communicating with their parents!
        </p>
        <p>In rare cases, this one-to-one communication can progress 
           to the point at which a shared language is created. 
           The twins will come up with their own words, and in some 
           cases, their own grammatical structures. The languages
           are unintelligible to anyone else but the twins. These cases 
           are very rare, even though they are well publicized. 
           The twin's secret language will usually disappear by age 
           4 or 5, as they become more adept at using their
           parent's language.
        </p>
        <p>What can you do to help your twins in acquiring 
           language? The most important thing you can do is pay 
           individual attention to each child. Easier said than
           done! Provide feedback to each child as he or she gropes 
           with language. If you are feeding your twins, talk to one 
           child as the other is eating. Then, when the first child 
           is eating, switch to the second. When changing
           diapers, use the one-on-one time (one hopes) to further 
           provide the audio clues needed for learning language.
        </p>
        <p>As with everything that is twin-related, language 
           acquisition requires some extra work on the part of the 
           parents; but again with twin-related activities,
           the extra work is paid off in extra fun.
        </p>
     </article>


     <footer>
        Twin Life Magazine: Issue 189; &copy; 2015 (US)
        <span>
           <a href="#">About</a>
           <a href="#">Terms</a>
           <a href="#">Help</a>
        </span>
     </footer>

  </section>