如何实现按钮点击修改元素font-family?已写代码求完善
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

