javascript - 如何在 Javascript 中使用 'ArrowUp' 增加表情符号的大小

标签 javascript dom

当用户按下向上箭头时,我尝试不断地将气球表情符号的大小增加 10px,并使用键盘上的向下箭头将大小减小 10px。

我一直在尝试设置:

let size = para.style.fontSize;

为了获取大小变量,然后通过在我的函数中添加 +/- 10px 来调整该值。不过我试过这个方法,好像不能设置:

para.style.fontSize = size +10;

有人有任何建议让它发挥作用吗?

注意:我没有在下面的代码中包含大小变量,因为我发现它不起作用。

<!DOCTYPE html>
<html>

<head>
  <title>Title of the document</title>
  <style>
    p {
      font-size: 50px;
    }
  </style>
</head>

<body>
  <p>🎈</p>

  <script>
    let para = document.querySelector('p');


    window.addEventListener("keydown", e => {
    if (e.key == "ArrowUp") {
      para.style.fontSize = '60px';
    } else {
      para.style.fontSize = '40px';
    }
  });



  </script>

</body>

</html>

最佳答案

要在多个 keydown 事件上实现增大/缩小行为,您需要递增/递减每个事件的 para.style.fontSize。完成此操作的方法如下:

<!DOCTYPE html>
<html>

<head>
  <title>Title of the document</title>
  <style>
    p {
      font-size: 50px;
    }
  </style>
</head>

<body>
  <p>🎈</p>

  <script>
    let para = document.querySelector('p');

    window.addEventListener("keydown", e => {

      let currentSize = parseInt(para.style.fontSize);

      // If unable to determine current fontSize, default to 50
      if (isNaN(currentSize)) {
        currentSize = 50;
      }

      // Define the rate of change
      let changeAmount = 5;

      if (e.key == "ArrowUp") {
        para.style.fontSize = (currentSize + changeAmount) + 'px';
      } else {
        // Protect againt zero or negative font sizes via Math.max() 
        para.style.fontSize = Math.max(changeAmount, currentSize - changeAmount) + 'px';
      }
    });
  </script>

</body>

</html>

关于javascript - 如何在 Javascript 中使用 'ArrowUp' 增加表情符号的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53938789/

相关文章:

javascript - 将 JavaScript 鼠标事件从一个元素传播到另一个元素?

javascript - 创建与其他函数链接的函数对象?

javascript - 为什么我的 thead 没有出现在 Internet Explorer 中?

javascript - ReactJS - 是从子组件提供参数更好,还是在父组件中提供参数更好 - 当回调相同时?

javascript - 从完整日历中获取点击日期

javascript - 验证电子邮件是否已成功发送 nodemailer (sails.js)

c# - 从 WebBrowser 访问 DOM

php - DomDocument 解析换行符适用于 span 但不适用于 img

javascript - AngularJS 应用程序 : make pagination take into account the standard filter

javascript - 我正在将一个 Prop 从 App.js 传递到 MovieCard.js,但传递的 Prop 显示为空