You need to enable JavaScript to run this app. 如何通过onclick点击事件修改task_box类下h2标签的字体与颜色
优惠活动
大模型
产品
解决方案
定价
更多

如何通过onclick点击事件修改task_box类下h2标签的字体与颜色

调整方案

你只需要修改JS代码里的元素选择逻辑即可,原有逻辑是选中label_1、label_2元素修改样式,我们替换为选中.task_box下的h2标签即可。

固定样式版本(直接写死红色+courier字体)

修改后的JS代码如下:

function swap_color_and_font() {
  // 精准匹配class为task_box的div下的h2元素
  const targetH2 = document.querySelector('.task_box h2')
  targetH2.style.color = "red"
  targetH2.style.fontFamily = "courier"
}

读取输入框自定义值版本(使用用户在输入框填写的颜色、字体)

如果需要响应用户在输入框中填写的配置,可以改成如下代码:

function swap_color_and_font() {
  const targetH2 = document.querySelector('.task_box h2')
  // 读取两个输入框的内容
  const customColor = document.getElementById('font_color').value.trim()
  const customFont = document.getElementById('font_family').value.trim()
  // 输入框为空时默认用红色、courier
  targetH2.style.color = customColor || 'red'
  targetH2.style.fontFamily = customFont || 'courier'
}

HTML补充修正

你当前的HTML代码存在两个小问题,可以同步修正:

  • 两个label标签没有闭合,需要补充结束标签内的文本和>
  • 第二个label的for属性值写错了,应该对应下方字体输入框的id:
<fieldset>
  <label for="font_color" id="label_1">字体颜色:</label><br/>
  <input type="text" id="font_color" value="" /><br/>
  <label for="font_family" id="label_2">字体类型:</label><br/>
  <input type="text" id="font_family" value="" /><br/>
  <input onclick="swap_color_and_font()" value="Change font and color" type="button" />
</fieldset>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.22 03:45:04