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

点击按钮设置表单<input>文本加粗失效问题求助

解决文本无法通过按钮设置加粗的问题

我来帮你排查下问题,主要有几个关键点导致你遇到这个情况:

1. jQuery toggle() 方法的版本兼容问题

你用的jQuery 2.1.1已经移除了旧版的toggle(fn1, fn2)事件切换方法(这个方法在jQuery 1.9+就被废弃了),现在的toggle()只是用来控制元素的显示/隐藏,所以你的事件绑定逻辑根本没生效。

2. font-weight: auto 不是有效值

CSS里font-weight没有auto这个合法取值,要取消加粗状态应该用normal。

3. 元素的样式特殊性

虽然大部分现代浏览器支持给设置font-weight,但如果你的样式被浏览器默认样式或其他自定义CSS覆盖,也可能出现不生效的情况——不过这不是核心问题,先把代码逻辑修好就能解决大部分场景的问题。

修正后的基础版代码

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="notes" value="测试文本">
<button class="bold_text">切换加粗</button>

<script>
$('.bold_text').click(function() {
  const $notes = $('#notes');
  // 检查当前是否为加粗状态,切换对应样式
  if ($notes.css('font-weight') === '700' || $notes.css('font-weight') === 'bold') {
    $notes.css('font-weight', 'normal');
  } else {
    $notes.css('font-weight', 'bold');
  }
});
</script>

更推荐的优化方案(用类管理样式)

直接操作CSS不如用类来控制样式更可靠,还能避免不同浏览器返回font-weight值的差异(有的返回数字700,有的返回字符串bold):

<style>
.text-bold {
  font-weight: bold !important; /* 确保覆盖浏览器默认样式 */
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="notes" value="测试文本">
<button class="bold_text">切换加粗</button>

<script>
$('.bold_text').click(function() {
  $('#notes').toggleClass('text-bold');
});
</script>

这个方法符合样式与逻辑分离的原则,后续维护也更方便。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:44:38