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

如何基于jQuery实现输入内容字符统计并按字符数添加对应样式类

Enhanced jQuery Solution for Dynamic Text Display & Font Sizing

Hey there! Let's upgrade your existing jQuery code to add character counting (including spaces) and apply different font sizes based on how many characters are entered. Here's the full implementation:

Step 1: Add CSS Classes for Font Sizes

First, define the styles we'll use for each character range:

.size-36 { font-size: 36px; }
.size-33 { font-size: 33px; }
.size-30 { font-size: 30px; }

Step 2: Updated jQuery Code

Here's the expanded JavaScript that handles the input, display, character count, and dynamic styling:

$(document).ready(function(){
  // Get value on button click and show text
  $("#myBtn").click(function(){
    var str = $("#name").val();
    var charCount = str.length; // Counts all characters, including spaces
    
    // Display the input text
    $('#one').html(str);
    
    // Remove any existing size classes first to avoid conflicts
    $('#one').removeClass('size-36 size-33 size-30');
    
    // Apply the correct class based on character count
    if (charCount >= 1 && charCount <= 3) {
      $('#one').addClass('size-36');
    } else if (charCount >= 4 && charCount <= 7) {
      $('#one').addClass('size-33');
    } else if (charCount >= 8 && charCount <= 12) {
      $('#one').addClass('size-30');
    }
    // Note: For empty input or counts over 12, no class is added (uses default styling)
  });
});

Key Details Explained:

  • Character Count: str.length gives us the total number of characters, including spaces and punctuation—exactly what you need.
  • Class Management: We first remove all size classes before adding the new one. This prevents multiple classes from stacking and causing unexpected styling issues.
  • Conditional Logic: The if-else checks target your specific character ranges, applying the corresponding font size class to the #one element.

If you want to handle counts over 12, you could add an extra else clause to apply a default size (like 24px) if needed!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 10:42:48