首页 > 解决方案 > 为什么在鼠标单击事件之前设置正文字体大小?

问题描述

为什么在鼠标单击事件之前设置正文字体大小?在下面的代码中。请解释。

<body>
<p>Some paragraph text</p>
<h1>some heading 1 text</h1>
<h2>some heading 2 text</h2>
<a href="#" id="size-12">12</a>
<script>
document.getElementById('size-12').onclick = (function(size){
    document.body.style.fontSize = size + 'px';
})(20);
</script>
</body>

标签: javascriptclosures

解决方案


简短的回答:

您的代码片段正在评估页面加载并返回undefined已分配给onclick事件。在单击任何 DOM 元素之前会更改该fontSize属性。从你的例子:

(function(size){
    document.body.style.fontSize = size + 'px';
})(20);

更长的解释:

让我们看一个简单的例子来表示代码的评估顺序:

(function () {
  let returnValue = (function(size){
                       console.log(`Look, I'm evaluated`);
                    })(20);
  
  console.log('Return value of the code snippet', returnValue);
})();

要消除此问题,您需要执行以下操作:

<script>
   document.getElementById('size-12').onclick = function {
      document.body.style.fontSize = '20px';
   };
</script>

通过进行此更改,您的代码将仅在用户单击 id 的 DOM 元素时运行size-12


推荐阅读