javascript - 为什么在鼠标单击事件之前设置正文字体大小?
问题描述
为什么在鼠标单击事件之前设置正文字体大小?在下面的代码中。请解释。
<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>
解决方案
简短的回答:
您的代码片段正在评估页面加载并返回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
。
推荐阅读
- python - 无法抓取 json() 类型的评论
- continuous-integration - 如何在管道中坚持使用 Gitlab CI Runner?
- mysql - Mysql - 在大表中慢一个更新查询
- redis - 为什么 Redis 对于 lindex、lpop 是 O(N)
- python - 模式搜索python函数没有给出预期的结果
- python - 有没有更好的方法从 subreddit 获得提交?
- c# - 统一前方位置 = 摄像机角度
- javascript - 将图片源从父组件转移到子组件vuejs
- reactjs - 打字稿:我如何重构[记录
| 空,记录 | 无效的]? - javascript - newMember.guild.channels.cache.find 在我的不和谐机器人代码中不起作用