使用JavaScript实现在用户输入时修改文本框字体
Hey Malik, no worries about the post format—let's get your textarea font sorted out!
First off, let's break down why your previous attempts weren't working:
- You don't need to listen to the
inputevent just to set a font (font styles apply to the entire textarea element, not individual characters being typed). - Trying to set
ev.target.styledirectly or accessingev.target.value.styleis incorrect:styleis a property of the textarea element itself, not its text content (which is just a string, so it has nostyleattribute). - When modifying element styles via JS, you should target specific style properties like
fontFamilyinstead of trying to overwrite the entirestyleobject.
The Simplest Fix: CSS (No JS Needed!)
If you don't strictly need JavaScript for this, just add a CSS rule for your textarea—it's the most efficient way:
#thoughts { font-family: "Nunito", sans-serif; }
Just make sure you've loaded the Nunito font first (e.g., add this to your HTML <head>):
<link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Nunito&display=swap">
If You Must Use JavaScript
If you need to set the font dynamically with JS (e.g., based on some user action), you only need to set it once when the page loads—no need to hook into the input event. Here's the correct code:
<div id="thoughts-textarea"> <label for="thoughts">Additional thoughts?</label><br> <textarea name="thoughts" id="thoughts" cols="30" rows="5" placeholder="Enter any comments here..."></textarea> </div> <script> document.addEventListener('DOMContentLoaded', function(){ const thoughts = document.getElementById("thoughts"); // Set the font family directly on the element thoughts.style.fontFamily = "Nunito, sans-serif"; }); </script>
If You Really Need the Input Event (Unlikely for This Use Case)
If for some reason you do need to trigger font changes on input (e.g., switching fonts based on input content), clean up your function like this:
document.addEventListener('DOMContentLoaded', function(){ const thoughts = document.getElementById("thoughts"); thoughts.addEventListener('input', updateFont); // Initialize the font on page load updateFont.call(thoughts); }); function updateFont(){ // `this` refers to the textarea element here this.style.fontFamily = "Nunito, sans-serif"; console.log("Font updated:", this.style.fontFamily); }
The key takeaway is: font styles are applied to the textarea element itself, not the text inside it. You don't need to re-apply the font every time the user types—once it's set, it stays in effect.
内容的提问来源于stack exchange,提问作者permalik

