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

使用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 input event just to set a font (font styles apply to the entire textarea element, not individual characters being typed).
  • Trying to set ev.target.style directly or accessing ev.target.value.style is incorrect: style is a property of the textarea element itself, not its text content (which is just a string, so it has no style attribute).
  • When modifying element styles via JS, you should target specific style properties like fontFamily instead of trying to overwrite the entire style object.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 08:16:18