记录技术成长,奔向未来!

编辑器代码块行号添加

一、修改js

// 高亮所有代码块(统一使用)
highlightCodeBlocks() {
    if (typeof hljs !== 'undefined') {
        const blocks = this.editorDiv.querySelectorAll('pre code');
        blocks.forEach((block, idx) => {
            block.removeAttribute('data-highlighted');
            hljs.highlightElement(block);
            
            // ===== 添加行号(增强版,避免破坏布局)=====
            const pre = block.parentNode;
            if (!pre || pre.classList.contains('hljs-line-numbers-added')) return;
            
            // 计算行数(基于换行符)
            const codeText = block.innerText;
            const lines = codeText.split('\n').length;
            if (lines <= 1) return; // 单行代码不加行号
            
            // 创建行号容器
            const lineNumbersDiv = document.createElement('div');
            lineNumbersDiv.className = 'hljs-line-numbers';
            lineNumbersDiv.setAttribute('aria-hidden', 'true');
            lineNumbersDiv.style.cssText = `
                float: left;
                text-align: right;
                padding-right: 10px;
                user-select: none;
                color: #888;
                background: inherit;
                border-right: 1px solid #444;
                margin-right: 10px;
                font-family: monospace;
                font-size: inherit;
                line-height: inherit;
            `;
            let numbers = '';
            for (let i = 1; i <= lines; i++) numbers += i + '\n';
            lineNumbersDiv.innerText = numbers;
            
            // 调整 pre 样式
            pre.style.position = 'relative';
            pre.style.overflow = 'auto';
            pre.style.display = 'flex';
            pre.style.flexDirection = 'row';
            pre.insertBefore(lineNumbersDiv, block);
            
            // 为 code 添加样式,使其自适应
            block.style.display = 'block';
            block.style.flex = '1';
            block.style.whiteSpace = 'pre';
            
            pre.classList.add('hljs-line-numbers-added');
        });
    }
}



二、修改css

/* 代码块行号样式 */
pre.hljs-line-numbers-added {
    display: flex !important;
    flex-direction: row !important;
    align-items: stretch !important;
    background: #2c3e50;  /* 与您的代码块背景色一致 */
    color: #f8f9fa;
    padding: 12px !important;
}

.hljs-line-numbers {
    float: none;
    text-align: right;
    padding-right: 15px;
    user-select: none;
    color: #8e9eaf;
    border-right: 1px solid #4a5b6e;
    background: inherit;
    font-family: monospace;
    font-size: 14px;
    line-height: 1.45;
    white-space: pre;
}

/* 确保 code 内容不溢出 */
pre code {
    display: block;
    flex: 1;
    overflow-x: auto;
    white-space: pre;
    font-family: monospace;
    font-size: 14px;
    line-height: 1.45;
}

/* 移动端适配 */
@media (max-width: 768px) {
    .hljs-line-numbers {
        padding-right: 8px;
        font-size: 12px;
    }
    pre code {
        font-size: 12px;
    }
}

发表评论 (0)

留下你的足迹

验证码 点击图片刷新