You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改代码实现网站所有段落字体大小的切换功能?

解决所有段落字体大小切换的问题

原代码的核心问题有两个:

  • HTML里多个<p>用了同一个id="p",但id在HTML中必须唯一,所以getElementById只能拿到第一个段落。
  • 函数只修改了单个段落的样式,没有处理所有段落。

下面是修改后的代码,实现点击按钮切换所有段落的字体大小:

<button type="button" onclick="change_font_size();">Change font size</button>
<p> this is some text </p>
<p> this is also some text </p>

<script>
var font_is_large = false ;
function change_font_size( )
{
  // 获取所有p标签元素
  const paragraphs = document.getElementsByTagName('p');
  // 遍历所有段落,逐个修改字体大小
  for (let p of paragraphs) {
    if (!font_is_large) {
      p.style.fontSize = "150%" ;
    }
    else {
      p.style.fontSize = "100%" ;
    }
  }
  // 切换状态
  font_is_large = !font_is_large;
}
</script>

改动说明:

  1. 去掉了p标签的重复id,避免HTML结构错误。
  2. 用document.getElementsByTagName('p')获取页面中所有的<p>元素,返回一个元素集合。
  3. 通过for...of循环遍历所有段落,逐个设置字体大小。
  4. 最后统一切换font_is_large的状态,保证所有段落的切换状态一致。

内容的提问来源于stack exchange,提问作者Swq242kwla32

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 14:40:33