JavaScript onclick() 文本大小随 EventListener 增加

标签 javascript html button action handler

我正在尝试实现以下内容以根据按钮点击增加文本大小。我正在尝试为此使用一个处理程序。这个想法是将“演示”区域中文本的字体大小增加/减少 +/-5 像素。但是我没有得到想要的结果。

<html>
    <body>
        <p>Change font size</p>
        <div id="main_area1">
            <button id="button1" value="larger" type="button" onclick="changeFontSize(this)">Larger</button>
        </div>
        <div id="main_area2">
            <button id="button2" vale="smaller" type="button" onclick="changeFontSize(this)">Smaller</button>
        </div>
        <div>
            <p id="demo">HOW_BIG_OR_SMALL_AM_I</p>
        </div>
        <script>
            function changeFontSize(target) {
                if (target == document.getElementById("button1")) {
                    document.getElementById("demo").style.fontSize = document.getElementById("demo").style.fontSize + "5px";
                } else if (target == document.getElementById("button2")) {
                    document.getElementById("demo").style.fontSize = document.getElementById("demo").style.fontSize + "-5px";
                }
            }
        </script>
    </body>
</html>

当我在开发人员控制台中检查它时,我看到我的目标与 button1 具有相同的 value。但是我看不到字体大小在增加(button2 也是如此)。

我尝试尽可能多地使用我的 Java 知识,但没有取得任何进展。我想我可能使用了错误的元素 ID,或者我没有正确注册处理程序。

感谢任何帮助或善意的建议!谢谢。

最佳答案

几点:

  1. style 对象不会有通过样式表应用的值;要获得这些,您可以在符合标准的浏览器上使用 getComputedStyle。 (在旧版 IE 上,您使用 currentStyle 属性。)

  2. 你需要解析你得到的值,因为它是一个字符串。

  3. 每当您发现自己一遍又一遍地重复写同一件事时,请考虑是否只做一次并将其记住在一个变量中。

这在符合标准的浏览器上有效并且应该也适用于旧的 IE:

function changeFontSize(target) {
  var demo = document.getElementById("demo");
  var computedStyle = window.getComputedStyle
        ? getComputedStyle(demo) // Standards
        : demo.currentStyle;     // Old IE
  var fontSize;

  if (computedStyle) { // This will be true on nearly all browsers
      fontSize = parseFloat(computedStyle && computedStyle.fontSize);

      if (target == document.getElementById("button1")) {
        fontSize += 5;
      } else if (target == document.getElementById("button2")) {
        fontSize -= 5;
      }
      demo.style.fontSize = fontSize + "px";
  }
}
<p>Change font size</p>
<div id="main_area1">
  <button id="button1" value="larger" type="button" onclick="changeFontSize(this)">Larger</button>
</div>
<div id="main_area2">
  <button id="button2" vale="smaller" type="button" onclick="changeFontSize(this)">Smaller</button>
</div>
<div>
  <p id="demo">HOW_BIG_OR_SMALL_AM_I</p>
</div>

关于JavaScript onclick() 文本大小随 EventListener 增加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26652595/

相关文章:

javascript - 那个讨厌的 HTML5 音频播放。我哪里错了?

JavaScript 代码未按预期在网页上运行

html - 带 Bootstrap 的半列

html - 如何在响应式 css 按钮中对齐文本中心?

javascript - 更改输入颜色元素类型的属性

javascript - 在javascript中转换对象数组

html - 无法让我的搜索图标位于搜索文本区域旁边

android设置定时器按钮的可见性

java - 使用jquery调用soap wsdl

javascript - 将主体的数据属性值分配给变量