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

如何实现按钮点击修改元素font-family?已写代码求完善

Fixing Your Font-Changing Button Script

Hey there! The problem with your current code is how you're targeting the font-family CSS property in JavaScript. Hyphenated property names don't work as direct identifiers in JS—here's how to fix it, with two straightforward solutions:

Solution 1: Use Camel Case (Standard Approach)

JavaScript converts hyphenated CSS properties to camel case for valid identifier usage, so replace font-family with fontFamily:

<button type="button" onclick="document.getElementById('idname').style.fontFamily = 'Georgia'"> Click Me!</button>

Solution 2: Bracket Notation

If you prefer keeping the hyphenated property name, wrap it in square brackets as a string:

<button type="button" onclick="document.getElementById('idname').style['font-family'] = 'Georgia'"> Click Me!</button>

Bonus: Cleaner Separation of JS and HTML

For better code maintainability, it's a good practice to move your JavaScript logic out of inline onclick attributes. Here's a more scalable version:

<h2 id="idname">My title</h2>
<button type="button" id="fontChangeBtn">Click Me!</button>

<script>
document.getElementById('fontChangeBtn').addEventListener('click', function() {
  const targetElement = document.getElementById('idname');
  targetElement.style.fontFamily = 'Georgia';
});
</script>

All these approaches will successfully update the font family of your <h2> element when the button is clicked.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 19:47:46