javascript文本长度检测与自动截取,用于标题长度检测

发布于:2025-09-15 ⋅ 阅读:(22) ⋅ 点赞:(0)

实时检测的效果,比较友好。

设计思路

  • 创建一个文本输入区域

  • 实时显示当前文本长度和最大允许长度

  • 当长度超过90时自动截取文本

  • 提供视觉反馈(进度条和颜色提示)

  • 实现代码

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文本长度检测与截取工具</title>
    <style>
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        body {
            background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
            min-height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }
        .container {
            background: white;
            border-radius: 12px;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
            width: 100%;
            max-width: 600px;
            padding: 30px;
        }
        h1 {
            color: #2c3e50;
            text-align: center;
            margin-bottom: 25px;
            font-weight: 600;
        }
        .input-container {
            margin-bottom: 20px;
        }
        textarea {
            width: 100%;
            height: 150px;
            padding: 15px;
            border: 2px solid #e0e0e0;
            border-radius: 8px;
            font-size: 16px;
            resize: vertical;
            transition: border-color 0.3s;
        }
        textarea:focus {
            outline: none;
            border-color: #3498db;
        }
        .counter {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-top: 15px;
            color: #555;
        }
        .progress-container {
            height: 8px;
            background: #f0f0f0;
            border-radius: 4px;
            margin-top: 5px;
            overflow: hidden;
        }
        .progress-bar {
            height: 100%;
            background: #3498db;
            border-radius: 4px;
            transition: width 0.3s, background 0.3s;
        }
        .warning {
            color: #e74c3c;
            font-weight: 500;
        }
        .rules {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 8px;
            margin-top: 20px;
            font-size: 14px;
            color: #555;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>文本长度检测与截取</h1>
        
        <div class="input-container">
            <textarea id="textInput" placeholder="请输入或粘贴文本..."></textarea>
            <div class="progress-container">
                <div class="progress-bar" id="progressBar"></div>
            </div>
            <div class="counter">
                <span>当前长度: <span id="currentLength">0</span>/90</span>
                <span id="warningText"></span>
            </div>
        </div>
        
        <div class="rules">
            <p><strong>计算规则:</strong> 汉字=3个单位,半角字符=1.5个单位,其他字符=2个单位</p>
        </div>
    </div>

    <script>
        const textInput = document.getElementById('textInput');
        const currentLengthElement = document.getElementById('currentLength');
        const progressBar = document.getElementById('progressBar');
        const warningText = document.getElementById('warningText');
        
        // 计算字符串长度(汉字=3,半角字符=1.5,其他=2)
        function calculateLength(str) {
            let totalLength = 0;
            
            for (let i = 0; i < str.length; i++) {
                const char = str[i];
                const charCode = char.charCodeAt(0);
                
                // 判断是否为汉字(Unicode范围)
                if (charCode >= 0x4E00 && charCode <= 0x9FFF) {
                    totalLength += 3;
                } 
                // 判断是否为半角字符(ASCII字符)
                else if (charCode >= 0x0000 && charCode <= 0x00FF) {
                    totalLength += 1.5;
                }
                // 其他字符(如全角符号等)
                else {
                    totalLength += 2;
                }
            }
            
            return totalLength;
        }
        
        // 截取字符串到指定长度
        function truncateString(str, maxLength) {
            if (calculateLength(str) <= maxLength) return str;
            
            let result = '';
            let currentLength = 0;
            
            for (let i = 0; i < str.length; i++) {
                const char = str[i];
                const charCode = char.charCodeAt(0);
                let charLength = 0;
                
                if (charCode >= 0x4E00 && charCode <= 0x9FFF) {
                    charLength = 3;
                } else if (charCode >= 0x0000 && charCode <= 0x00FF) {
                    charLength = 1.5;
                } else {
                    charLength = 2;
                }
                
                if (currentLength + charLength > maxLength) {
                    break;
                }
                
                result += char;
                currentLength += charLength;
            }
            
            return result;
        }
        
        // 更新界面显示
        function updateDisplay() {
            const text = textInput.value;
            const length = calculateLength(text);
            
            // 更新长度显示
            currentLengthElement.textContent = length.toFixed(1);
            
            // 更新进度条
            const percentage = Math.min(100, (length / 90) * 100);
            progressBar.style.width = percentage + '%';
            
            // 更新警告文本和颜色
            if (length > 90) {
                currentLengthElement.className = 'warning';
                progressBar.style.background = '#e74c3c';
                warningText.textContent = '文本已超过限制,已自动截取';
                warningText.className = 'warning';
                
                // 截取文本
                const truncatedText = truncateString(text, 90);
                textInput.value = truncatedText;
                
                // 更新显示为截取后的长度
                const newLength = calculateLength(truncatedText);
                currentLengthElement.textContent = newLength.toFixed(1);
                progressBar.style.width = Math.min(100, (newLength / 90) * 100) + '%';
            } else {
                currentLengthElement.className = '';
                progressBar.style.background = '#3498db';
                warningText.textContent = '';
            }
        }
        
        // 添加输入事件监听
        textInput.addEventListener('input', updateDisplay);
        
        // 初始化显示
        updateDisplay();
    </script>
</body>
</html>

代码可以直接运行!!~~~!!!

功能说明

  1. 实时长度计算:在输入或粘贴文本时,实时计算文本长度(汉字=3,半角字符=1.5,其他字符=2)

  2. 自动截取:当文本长度超过90时,自动截取文本到合适长度

  3. 视觉反馈

    • 进度条显示当前文本长度占比

    • 颜色变化提示(蓝色正常,红色超过限制)

    • 显示警告信息当文本超过限制时

使用方法

  1. 在文本框中输入或粘贴文本

  2. 观察实时长度计算和进度条变化

  3. 当长度超过90时,文本会自动截取到合适长度