中文語音標註 HTML 生成器(拼音、注音)

Last updated on 9/7/2025@mrbirddev

語音指南

預覽:

(hàn)()(ㄓㄨㄥ)(ㄨㄣˊ)

原始 HTML:

在中文語言學習和數字排版的世界中,將語音標註顯示在漢字旁邊變得越來越重要。無論您是在創建教育內容、字典還是學習資源,正確實施拼音注音(Bopomofo)標註都能顯著提升用戶體驗。本綜合指南將引導您了解在網頁上顯示中文語音符號的各種方法、最佳實踐和技術考量。

了解中文語音系統

在深入實施之前,了解用於普通話的兩種主要語音標註系統是至關重要的:

拼音是使用拉丁字母和聲調符號來表示中文發音的羅馬化系統。例如,字符汉表示為帶有第四聲調符號的 "hàn"。

注音(注音符號),也稱為 Bopomofo,是一種使用從漢字衍生的獨特符號的語音系統。同一字符汉在注音中表示為 "ㄏㄢˋ"。

HTML Ruby 標籤:基礎

顯示語音標註的最語義化和標準化的方法是使用 HTML ruby 標籤。ruby 標記由三個主要元素組成:

  • <ruby>:用來包裹基礎文本及其註釋的容器元素
  • <rt>:包含顯示在基礎文本上方或旁邊的注音文字
  • <rp>:為不支援 ruby 註釋的瀏覽器提供備用的括號

基本 Ruby 實作

以下是實作 ruby 註釋的基本結構:

<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>Chinese Phonetic Annotations</title>
</head>
<body>
    <!-- Basic Pinyin annotation -->
    <ruby>
        汉<rp>(</rp><rt>hàn</rt><rp>)</rp>
    </ruby>
    <ruby>
        语<rp>(</rp><rt>yǔ</rt><rp>)</rp>
    </ruby>
    <ruby>
        拼<rp>(</rp><rt>pīn</rt><rp>)</rp>
    </ruby>
    <ruby>
        音<rp>(</rp><rt>yīn</rt><rp>)</rp>
    </ruby>

    <!-- Zhuyin annotation -->
    <ruby>
        中<rp>(</rp><rt>ㄓㄨㄥ</rt><rp>)</rp>
    </ruby>
    <ruby>
        文<rp>(</rp><rt>ㄨㄣˊ</rt><rp>)</rp>
    </ruby>
</body>
</html>

<rp> 標籤確保不支援 ruby 的瀏覽器會在括號中顯示注音,提供一個優雅的備用方案。

瀏覽器相容性與支援

現代瀏覽器對 ruby 註釋的支援程度差異顯著:

  • Firefox:自版本 38 起完全支援 ruby 註釋
  • Chrome/Chromium:自版本 5 起部分支援,並持續改進
  • Safari:自版本 5 起部分支援
  • Edge:自版本 12 起部分支援

「部分支援」通常意味著基本的 ruby 功能可用,但像是複雜的 ruby 佈局或特定定位等進階功能可能尚未完全實作。

CSS 樣式與定位

CSS 提供強大的工具來自訂 ruby 註釋的外觀和定位,這對於傳統上顯示在字元右側的注音符號特別重要。

基本 Ruby 樣式

ruby {
    font-size: 1.2em;
    line-height: 1.4;
}

rt {
    font-size: 0.7em;
    color: #666;
    font-weight: normal;
}

/* Styling for Chinese characters */
.chinese-text {
    color: #333;
    font-weight: 500;
}

/* Styling for pinyin */
.pinyin-text {
    color: #d32f2f;
    font-style: italic;
}

定位注音符號 (Zhuyin)

傳統的注音符號佈局需要垂直定位在字元的右側。這可以使用 ruby-position 屬性來實現:

/* For Bopomofo positioning */
.bopomofo ruby {
    ruby-position: inter-character;
}

/* Alternative approach for better browser support */
.bopomofo-vertical {
    writing-mode: vertical-rl;
    text-orientation: upright;
}

/* Custom positioning when ruby-position isn't supported */
.custom-bopomofo {
    position: relative;
    display: inline-block;
}

.custom-bopomofo rt {
    position: absolute;
    right: -1.5em;
    top: 0;
    writing-mode: vertical-rl;
    font-size: 0.6em;
    line-height: 1.2;
}

中文注音符號的 Unicode 編碼

正確的 Unicode 編碼對於在不同平台和設備上正確顯示中文注音符號至關重要。

拼音 Unicode 範圍

拼音使用標準拉丁字母與結合附加符號:

  • 第一聲(平聲): ā, ē, ī, ō, ū (長音符號: U+0304)
  • 第二聲(上升): á, é, í, ó, ú (尖音符號: U+0301)
  • 第三聲(降升): ǎ, ě, ǐ, ǒ, ǔ (抑揚符號: U+030C)
  • 第四聲(下降): à, è, ì, ò, ù (重音符號: U+0300)
<!-- HTML numeric character references for Pinyin -->
&#257; <!-- ā -->
&#225; <!-- á -->
&#462; <!-- ǎ -->
&#224; <!-- à -->

注音符號的 Unicode 範圍

注音符號被編碼在 Unicode 的注音符號區塊 (U+3100–U+312F):

  • 聲母: ㄅ(U+3105), ㄆ(U+3106), ㄇ(U+3107), 等等。
  • 韻母: ㄚ(U+311A), ㄛ(U+311B), ㄜ(U+311C), 等等。
  • 聲調符號: ˊ(U+02CA), ˇ(U+02C7), ˋ(U+02CB)
<!-- Ensure proper UTF-8 encoding -->
<meta charset="UTF-8">

<!-- Example Bopomofo characters -->
<span>ㄅㄆㄇㄈ</span> <!-- Consonants -->
<span>ㄚㄛㄜㄝ</span> <!-- Vowels -->
<span>ˊˇˋ˙</span>   <!-- Tone marks -->

JavaScript 函式庫與自動化

多個 JavaScript 函式庫可以自動生成拼音註釋,大大減少手動工作:

使用 pinyin-pro 函式庫

pinyin-pro 函式庫提供高準確性和豐富的拼音生成功能:

import { pinyin, html } from 'pinyin-pro';

// Generate Pinyin with tone marks
const pinyinResult = pinyin('汉语拼音', { toneType: 'symbol' });
console.log(pinyinResult); // 'hàn yǔ pīn yīn'

// Generate HTML with ruby tags
const htmlResult = html('汉语拼音');
// Returns properly formatted HTML with ruby annotations

自動 Ruby 生成

function addPinyinToText(chineseText) {
    const characters = chineseText.split('');
    let result = '';

    characters.forEach(char => {
        if (/[\u4e00-\u9fff]/.test(char)) {
            const pinyinChar = pinyin(char, { toneType: 'symbol' });
            result += `<ruby>${char}<rp>(</rp><rt>${pinyinChar}</rt><rp>)</rp></ruby>`;
        } else {
            result += char;
        }
    });

    return result;
}

// Usage
document.getElementById('chinese-content').innerHTML =
    addPinyinToText('学习中文很有趣');

注音符號生成

// Using a Zhuyin conversion library
function addZhuyinToText(chineseText) {
    const characters = chineseText.split('');
    let result = '';

    characters.forEach(char => {
        if (/[\u4e00-\u9fff]/.test(char)) {
            const zhuyinChar = convertToZhuyin(char); // Custom function
            result += `<ruby class="bopomofo">${char}<rp>(</rp><rt>${zhuyinChar}</rt><rp>)</rp></ruby>`;
        } else {
            result += char;
        }
    });

    return result;
}

字體考量

由於中文網頁字體的文件大小較大且需要支持數千個字符,因此需要特別考量。

中英文混合內容的字體堆疊

/* Recommended font stack */
.mixed-content {
    font-family:
        "SF Pro Text",
        "Helvetica Neue",
        Arial,
        "PingFang SC",
        "Microsoft YaHei",
        "微软雅黑",
        "STHeitiSC-Light",
        "华文黑体",
        sans-serif;
}

/* Specific fonts for phonetic symbols */
.pinyin {
    font-family:
        "Times New Roman",
        "Lucida Grande",
        serif;
}

.zhuyin {
    font-family:
        "DFKai-SB",
        "BiauKai",
        "標楷體",
        "AR PL UKai CN",
        serif;
}

避免字體加載問題

在中國大陸,Google 字體和其他外部字體服務可能被封鎖或速度緩慢。考慮以下替代方案:

/* Self-hosted fonts */
@font-face {
    font-family: 'CustomChinese';
    src: url('./fonts/chinese-regular.woff2') format('woff2'),
         url('./fonts/chinese-regular.woff') format('woff');
    font-display: swap; /* Improve loading performance */
}

/* Subset fonts for better performance */
@font-face {
    font-family: 'ChineseSubset';
    src: url('./fonts/chinese-common-chars.woff2') format('woff2');
    unicode-range: U+4E00-9FFF; /* Common Chinese characters */
}

進階佈局技術

拼音註釋的響應式設計

/* Responsive adjustments */
@media (max-width: 768px) {
    ruby {
        font-size: 1em;
    }

    rt {
        font-size: 0.6em;
    }

    /* Stack annotations vertically on small screens */
    .mobile-stack ruby {
        display: block;
        text-align: center;
        margin-bottom: 0.5em;
    }
}

/* High-density displays */
@media (-webkit-min-device-pixel-ratio: 2) {
    rt {
        font-weight: 400; /* Slightly bolder for clarity */
    }
}

垂直文字佈局

針對傳統中文佈局的垂直文字:

.vertical-chinese {
    writing-mode: vertical-rl;
    text-orientation: upright;

    /* Bopomofo positioning in vertical layout */
    ruby {
        ruby-position: inter-character;
    }

    rt {
        writing-mode: vertical-rl;
        text-orientation: upright;
    }
}

無障礙和SEO考量

螢幕閱讀器支援

<!-- Provide pronunciation information for screen readers -->
<ruby>
    中
    <rp>(</rp>
    <rt aria-label="pronounced zhong, first tone">zhōng</rt>
    <rp>)</rp>
</ruby>

<!-- Alternative with hidden pronunciation guide -->
<span>
    中<span class="sr-only">(zhōng)</span>
</span>

SEO友好的實施

<!-- Include both characters and pronunciation in meta content -->
<meta name="description" content="Learn Chinese 中文 (Zhōngwén) with phonetic guides">

<!-- Use appropriate language tags -->
<html lang="zh-CN"> <!-- Simplified Chinese -->
<html lang="zh-TW"> <!-- Traditional Chinese -->

<!-- Structured data for language learning content -->
<script type="application/ld+json">
{
    "@context": "http://schema.org ",
    "@type": "EducationalResource",
    "name": "Chinese Pronunciation Guide",
    "description": "Interactive guide for Chinese phonetic symbols",
    "inLanguage": "zh-CN",
    "educationalLevel": "Beginner"
}
</script>

效能優化

大型文件的延遲加載

// Implement lazy loading for phonetic annotations
const observer = new IntersectionObserver((entries) => {
    entries.forEach(entry => {
        if (entry.isIntersecting) {
            const element = entry.target;
            const chineseText = element.textContent;
            element.innerHTML = addPinyinToText(chineseText);
            observer.unobserve(element);
        }
    });
});

// Observe elements that need phonetic annotations
document.querySelectorAll('.needs-pinyin').forEach(el => {
    observer.observe(el);
});

語音數據快取

// Cache frequently used phonetic conversions
const pinyinCache = new Map();

function getCachedPinyin(character) {
    if (pinyinCache.has(character)) {
        return pinyinCache.get(character);
    }

    const result = pinyin(character, { toneType: 'symbol' });
    pinyinCache.set(character, result);
    return result;
}

跨瀏覽器測試和回退

功能檢測

// Detect ruby support
function supportsRuby() {
    const test = document.createElement('ruby');
    const rt = document.createElement('rt');
    const rp = document.createElement('rp');

    test.appendChild(rp);
    test.appendChild(rt);
    test.appendChild(rp);

    document.body.appendChild(test);

    const supported = (
        window.getComputedStyle(test).display === 'ruby' ||
        window.getComputedStyle(rt).display === 'ruby-text'
    );

    document.body.removeChild(test);
    return supported;
}

// Provide fallback for unsupported browsers
if (!supportsRuby()) {
    // Implement custom ruby layout with CSS
    const rubyElements = document.querySelectorAll('ruby');
    rubyElements.forEach(ruby => {
        ruby.classList.add('ruby-fallback');
    });
}

CSS回退

/* Fallback styles for browsers without ruby support */
.ruby-fallback {
    position: relative;
    display: inline-block;
    text-align: center;
    vertical-align: baseline;
}

.ruby-fallback rt {
    position: absolute;
    top: -1.2em;
    left: 50%;
    transform: translateX(-50%);
    font-size: 0.7em;
    line-height: 1;
    white-space: nowrap;
}

.ruby-fallback rp {
    display: none;
}

/* Show parentheses when ruby is completely unsupported */
.no-ruby .ruby-fallback rp {
    display: inline;
}

.no-ruby .ruby-fallback rt {
    position: static;
    transform: none;
    font-size: 0.8em;
}

實際應用範例

教育網站

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Chinese Learning Platform</title>
    <style>
        .lesson-content ruby {
            color: #2c3e50;
            font-size: 1.3em;
            margin: 0 0.1em;
        }

        .lesson-content rt {
            color: #e74c3c;
            font-size: 0.65em;
            font-weight: 500;
        }

        .highlight-tones .tone1 { color: #f1c40f; }
        .highlight-tones .tone2 { color: #e67e22; }
        .highlight-tones .tone3 { color: #e74c3c; }
        .highlight-tones .tone4 { color: #9b59b6; }
    </style>
</head>
<body>
    <div class="lesson-content highlight-tones">
        <h2>今天的课程 (Today's Lesson)</h2>
        <p>
            <ruby>今<rp>(</rp><rt class="tone1">jīn</rt><rp>)</rp></ruby>
            <ruby>天<rp>(</rp><rt class="tone1">tiān</rt><rp>)</rp></ruby>
            <ruby>我<rp>(</rp><rt class="tone3">wǒ</rt><rp>)</rp></ruby>
            <ruby>们<rp>(</rp><rt class="tone2">mén</rt><rp>)</rp></ruby>
            <ruby>学<rp>(</rp><rt class="tone2">xué</rt><rp>)</rp></ruby>
            <ruby>习<rp>(</rp><rt class="tone2">xí</rt><rp>)</rp></ruby>
            <ruby>中<rp>(</rp><rt class="tone1">zhōng</rt><rp>)</rp></ruby>
            <ruby>文<rp>(</rp><rt class="tone2">wén</rt><rp>)</rp></ruby>
        </p>
    </div>
</body>
</html>

互動字典

class ChineseDictionary {
    constructor() {
        this.pinyinCache = new Map();
        this.zhuyinCache = new Map();
    }

    async loadPhoneticData() {
        // Load phonetic conversion data
        const response = await fetch('/api/phonetic-data');
        const data = await response.json();

        data.forEach(entry => {
            this.pinyinCache.set(entry.character, entry.pinyin);
            this.zhuyinCache.set(entry.character, entry.zhuyin);
        });
    }

    createAnnotatedText(text, type = 'pinyin') {
        const characters = text.split('');
        const cache = type === 'pinyin' ? this.pinyinCache : this.zhuyinCache;

        return characters.map(char => {
            if (/[\u4e00-\u9fff]/.test(char)) {
                const annotation = cache.get(char) || '';
                return `<ruby class="${type}">${char}<rp>(</rp><rt>${annotation}</rt><rp>)</rp></ruby>`;
            }
            return char;
        }).join('');
    }

    toggleAnnotationType(element, type) {
        const text = element.textContent.replace(/[()]/g, '');
        element.innerHTML = this.createAnnotatedText(text, type);
    }
}

// Usage
const dictionary = new ChineseDictionary();
dictionary.loadPhoneticData().then(() => {
    // Enable interactive annotation switching
    const toggleButtons = document.querySelectorAll('.annotation-toggle');
    toggleButtons.forEach(button => {
        button.addEventListener('click', (e) => {
            const target = document.querySelector(e.target.dataset.target);
            const type = e.target.dataset.type;
            dictionary.toggleAnnotationType(target, type);
        });
    });
});

結論

在網頁上實施中文注音符號需要仔細考慮HTML語義、CSS樣式、瀏覽器相容性和效能優化。HTML的ruby元素提供了最語義化和可訪問的基礎,而CSS則提供了廣泛的定位和外觀自訂選項。

成功實施的關鍵要點:

  1. 使用語義化HTML,使用ruby、rt和rp標籤來建立正確結構
  2. 為支援有限的瀏覽器實施適當的回退
  3. 考慮字體加載和效能影響,特別是針對中國市場
  4. 在多個瀏覽器和設備上進行測試以確保一致的體驗
  5. 適當時利用JavaScript庫進行自動語音生成
  6. 通過適當的標記和元數據優化無障礙和SEO

無論您是在構建教育平台、數位字典,還是語言學習工具,這些技術都將幫助您創建專業、易於訪問且使用者友好的中文拼音註釋實現。現代網頁標準、周到的設計和性能優化的結合,確保您的拼音註釋能夠在不同的平台和使用者環境中可靠運行。

請記住,東亞語言的網頁排版領域不斷發展,新的 CSS 功能和瀏覽器能力正在開發中。保持對 CSS Writing Modes、字體技術和 Unicode 標準的最新發展的了解,以保持您的實現方式的現代性和有效性。

Last updated on 9/7/2025@mrbirddev
Loading...