Bible.com iframe specific styles

Adds a class to html if bible.com is in an iframe. Adjusts font size of parallel versions to fit the left column. Accepts parent scrolling messages.

当前为 2025-05-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Bible.com iframe specific styles
  3. // @namespace Violentmonkey Scripts
  4. // @match *://www.bible.com/*
  5. // @grant none
  6. // @version 2.0b
  7. // 改善字體大細个調整成功率、增加單節頁面/歸章頁面連結撳鈕
  8. // @author Aiuanyu x Gemini
  9. // @description Adds a class to html if bible.com is in an iframe. Adjusts font size of parallel versions to fit the left column. Accepts parent scrolling messages.
  10. // @description:zh-TW 當 bible.com 在 iframe 裡時,給 <html> 加個 class。調整並列版本个字體大小,讓佇左邊个欄位內看起來較好。接受上層網頁共下捲動个命令。
  11. // ==/UserScript==
  12.  
  13. (function() {
  14. 'use strict';
  15.  
  16. const multiVersionLinkId = 'multi-version-link'; // Define globally within the IIFE
  17. let topWindowObserver = null; // To hold the observer for the top window
  18. let lastCheckedHrefForPolling = location.href; // For URL polling
  19.  
  20. if (window.self !== window.top) {
  21. document.documentElement.classList.add('is-in-iframe');
  22. console.log('Bible.com 在 iframe 內,已為 <html> 加入 "is-in-iframe" class。');
  23.  
  24. // 當 iframe 內容載入完成後,嘗試調整並列版本个字體大小
  25. window.addEventListener('load', function () {
  26. // 等待所有字體載入完成 (e.g., web fonts used by bible.com itself)
  27. document.fonts.ready.then(function () {
  28. // Add a small delay AFTER fonts are ready and page is loaded,
  29. // to give bible.com's own scripts more time to render dynamic content
  30. // before we start measuring heights.
  31. const initialAdjustmentDelay = 1500; // 1.5 秒
  32. console.log(`所有字體載入完成。等待 ${initialAdjustmentDelay}ms 後嘗試調整字體。`);
  33. setTimeout(function() {
  34. adjustParallelFontSize();
  35. }, initialAdjustmentDelay);
  36. }).catch(function (error) {
  37. console.warn('字體載入錯誤或超時,仍嘗試調整字體:', error);
  38. setTimeout(function() { adjustParallelFontSize(); }, 1500); // 若有錯誤,也延遲一下再試
  39. });
  40. });
  41. // 監聽來自父視窗 (index.html) 的訊息
  42. window.addEventListener('message', function(event) {
  43. // 為著安全,可以檢查訊息來源 event.origin
  44. // 但因為 index.html 可能係 file:// 協定,event.origin 會係 'null'
  45. // 所以,檢查 event.source 是不是 window.top 會較穩當
  46. // if (event.source !== window.top) { // 暫時允許任何來源,方便本地測試
  47. // console.log('Userscript: Message ignored, not from top window or expected origin.');
  48. // return;
  49. // }
  50.  
  51. if (event.data && event.data.type === 'SYNC_SCROLL_TO_PERCENTAGE') {
  52. const percentage = parseFloat(event.data.percentage);
  53. if (isNaN(percentage) || percentage < 0 || percentage > 1) {
  54. console.warn('Userscript: 收到無效个捲動百分比:', event.data.percentage);
  55. return;
  56. }
  57.  
  58. const de = document.documentElement;
  59. const scrollableDistance = de.scrollHeight - de.clientHeight;
  60. if (scrollableDistance <= 0) {
  61. // console.log('Userscript: 內容毋需捲動。');
  62. return;
  63. }
  64. const scrollToY = scrollableDistance * percentage;
  65. // console.log(`Userscript: Scrolling to ${percentage*100}%, ${scrollToY}px. Scrollable: ${scrollableDistance}, Total: ${de.scrollHeight}, Visible: ${de.clientHeight}`);
  66. window.scrollTo({ top: scrollToY, behavior: 'auto' }); // 'auto' 表示立即捲動
  67. }
  68. });
  69.  
  70. } else {
  71. console.log('Bible.com 為頂層視窗。');
  72. // 當 bible.com 在頂層視窗時,執行个邏輯 (等待 DOM 載入完成)
  73. if (document.readyState === 'loading') {
  74. document.addEventListener('DOMContentLoaded', mainTopWindowLogic);
  75. } else {
  76. mainTopWindowLogic(); // DOM 已載入
  77. }
  78. }
  79.  
  80. function mainTopWindowLogic() {
  81. console.log('DOM 已就緒,初始化頂層視窗个多版本連結邏輯。');
  82. // 初次嘗試加入/更新連結
  83. addOrUpdateMultiVersionLink();
  84.  
  85. // 設定 MutationObserver 來監測 DOM 變化
  86. if (topWindowObserver) {
  87. topWindowObserver.disconnect();
  88. }
  89. topWindowObserver = new MutationObserver((mutations) => {
  90. // 任何 DOM 變化都可能影響目標或 URL,所以重新執行檢查邏輯
  91. // console.log('偵測到 Body 內容變動,重新評估連結狀態。'); // 這訊息可能會太頻繁
  92. addOrUpdateMultiVersionLink();
  93. });
  94.  
  95. // 監測 body 元素个子節點列表及子樹變化
  96. topWindowObserver.observe(document.body, { childList: true, subtree: true });
  97.  
  98. // 監聽瀏覽歷史變化事件
  99. window.addEventListener('popstate', () => { console.log('popstate 事件觸發,重新評估連結狀態。'); addOrUpdateMultiVersionLink(); });
  100. window.addEventListener('hashchange', () => { console.log('hashchange 事件觸發,重新評估連結狀態。'); addOrUpdateMultiVersionLink(); });
  101.  
  102. // 定時檢查 URL 變化 (作為 pushState 等事件个備援方案)
  103. setInterval(() => {
  104. if (location.href !== lastCheckedHrefForPolling) {
  105. console.log(`偵測到 URL 變化 (輪詢):${lastCheckedHrefForPolling} -> ${location.href},重新評估連結狀態。`);
  106. lastCheckedHrefForPolling = location.href;
  107. addOrUpdateMultiVersionLink();
  108. }
  109. }, 1000); // 每秒檢查一次
  110. }
  111.  
  112. // 取得書卷个中文顯示名稱 (Hakka/Traditional Chinese)
  113. function getBookDisplayName(bookCode) {
  114. const bookMap = {
  115. // Old Testament - 舊約
  116. "GEN": "創世記", "EXO": "出埃及記", "LEV": "利未記", "NUM": "民數記", "DEU": "申命記",
  117. "JOS": "約書亞記", "JDG": "士師記", "RUT": "路得記", "1SA": "撒母耳記上", "2SA": "撒母耳記下",
  118. "1KI": "列王紀上", "2KI": "列王紀下", "1CH": "歷代志上", "2CH": "歷代志下", "EZR": "以斯拉記",
  119. "NEH": "尼希米記", "EST": "以斯帖記", "JOB": "約伯記", "PSA": "詩篇", "PRO": "箴言",
  120. "ECC": "傳道書", "SNG": "雅歌", "ISA": "以賽亞書", "JER": "耶利米書", "LAM": "耶利米哀歌",
  121. "EZK": "以西結書", "DAN": "但以理書", "HOS": "何西阿書", "JOL": "約珥書", "AMO": "阿摩司書",
  122. "OBA": "俄巴底亞書", "JON": "約拿書", "MIC": "彌迦書", "NAM": "那鴻書", "HAB": "哈巴谷書",
  123. "ZEP": "西番雅書", "HAG": "哈該書", "ZEC": "撒迦利亞書", "MAL": "瑪拉基書",
  124. // New Testament - 新約
  125. "MAT": "馬太福音", "MRK": "馬可福音", "LUK": "路加福音", "JHN": "約翰福音", "ACT": "使徒行傳",
  126. "ROM": "羅馬書", "1CO": "哥林多前書", "2CO": "哥林多後書", "GAL": "加拉太書", "EPH": "以弗所書",
  127. "PHP": "腓立比書", "COL": "歌羅西書", "1TH": "帖撒羅尼迦前書", "2TH": "帖撒羅尼迦後書",
  128. "1TI": "提摩太前書", "2TI": "提摩太後書", "TIT": "提多書", "PHM": "腓利門書", "HEB": "希伯來書",
  129. "JAS": "雅各書", "1PE": "彼得前書", "2PE": "彼得後書", "1JN": "約翰一書", "2JN": "約翰二書",
  130. "3JN": "約翰三書", "JUD": "猶大書", "REV": "啟示錄"
  131. };
  132. return bookMap[bookCode.toUpperCase()] || bookCode; // 若尋無對應,就用原底个 bookCode
  133. }
  134.  
  135. function addOrUpdateMultiVersionLink() {
  136. const url = window.location.href;
  137. // Regex to capture book (e.g., PSA), chapter (e.g., 18), and verse (e.g., 2)
  138. const singleVerseRegex = /\/bible\/\d+\/([A-Z1-3]{3})\.(\d+)\.(\d+)/;
  139. // Regex for chapter page: book.chapter (potentially followed by version info, but not another verse number)
  140. const chapterPageRegex = /\/bible\/\d+\/([A-Z1-3]{3})\.(\d+)/;
  141.  
  142. const singleVerseMatch = url.match(singleVerseRegex);
  143. const targetDivSelector = 'div.flex.flex-col.md\\:flex-row.items-center.gap-2.mbs-3';
  144. const existingInlineLink = document.getElementById(multiVersionLinkId); // 修正變數名稱
  145. const floatingButtonId = 'multi-version-chapter-float-btn'; // 新增浮動撳鈕个 ID
  146. const existingFloatingButton = document.getElementById(floatingButtonId);
  147.  
  148. if (singleVerseMatch) {
  149. // 係單節經文頁面
  150. const book = singleVerseMatch[1];
  151. const chapter = singleVerseMatch[2];
  152. const bookNameToDisplay = getBookDisplayName(book);
  153. const targetDiv = document.querySelector(targetDivSelector);
  154.  
  155. // 移除可能存在个浮動章節連結
  156. if (existingFloatingButton) {
  157. console.log('單節經文頁面,移除浮動章節連結。');
  158. existingFloatingButton.remove();
  159. }
  160.  
  161. if (!targetDiv) {
  162. if (existingInlineLink) {
  163. console.log('單節經文頁面,目標 <div> 未尋到,移除可能殘留个內嵌連結。');
  164. existingInlineLink.remove();
  165. }
  166. return;
  167. }
  168.  
  169. const expectedHref = `https://aiuanyu.github.io/6BibleVersions/?book=${book}&chapter=${chapter}`;
  170. const expectedTextContent = `4 語言 6 版本對照讀 ${bookNameToDisplay} ${chapter}`;
  171.  
  172. if (existingInlineLink) {
  173. // 內嵌連結已存在,檢查並更新
  174. let updated = false;
  175. // 檢查係毋係在正確个位置 (第一個子元素)
  176. if (existingInlineLink.parentElement !== targetDiv || existingInlineLink !== targetDiv.firstChild) {
  177. targetDiv.insertBefore(existingInlineLink, targetDiv.firstChild);
  178. updated = true;
  179. }
  180. if (existingInlineLink.href !== expectedHref) {
  181. existingInlineLink.href = expectedHref;
  182. updated = true;
  183. }
  184. const pElement = existingInlineLink.querySelector('p');
  185. if (pElement && pElement.textContent !== expectedTextContent) {
  186. pElement.textContent = expectedTextContent;
  187. updated = true;
  188. }
  189. if (updated) console.log(`內嵌連結已更新: ${bookNameToDisplay} ${chapter}`);
  190. } else {
  191. // 內嵌連結毋存在,建立並加入
  192. const newLink = document.createElement('a');
  193. newLink.className = "overflow-hidden font-bold ease-in-out duration-100 focus:outline-2 focus:outline-info-light dark:focus:outline-info-dark hover:shadow-light-2 disabled:text-gray-50 dark:disabled:bg-gray-40 dark:disabled:text-white disabled:hover:shadow-none disabled:opacity-50 disabled:bg-gray-10 disabled:cursor-not-allowed w-full max-w-fit bg-gray-15 dark:bg-gray-35 text-gray-50 dark:text-white hover:bg-gray-10 dark:hover:bg-gray-30 active:bg-gray-20 dark:active:bg-gray-40 rounded-3 text-xs pis-2 pie-3 h-6 cursor-pointer flex md:w-min items-center group static no-underline";
  194. newLink.href = expectedHref;
  195. newLink.target = '_blank';
  196. newLink.rel = 'noopener noreferrer';
  197. newLink.id = multiVersionLinkId;
  198.  
  199. const svgString = `
  200. <svg width="24" height="24" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg" class="flex-shrink-0 mie-0.5" size="24">
  201. <path d="M16 3H5C3.89543 3 3 3.89543 3 5V16H5V5H16V3Z" style="--darkreader-inline-fill: currentColor;" data-darkreader-inline-fill=""></path>
  202. <path d="M20 7H9C7.89543 7 7 7.89543 7 9V20C7 21.1046 7.89543 22 9 22H20C21.1046 22 22 21.1046 22 20V9C22 7.89543 21.1046 7 20 7ZM20 20H9V9H20V20Z" style="--darkreader-inline-fill: currentColor;" data-darkreader-inline-fill=""></path>
  203. </svg>`;
  204. const tempDiv = document.createElement('div');
  205. tempDiv.innerHTML = svgString.trim();
  206. const svgElement = tempDiv.firstChild;
  207. if (svgElement) newLink.appendChild(svgElement);
  208.  
  209. const textSpan = document.createElement('span');
  210. textSpan.className = 'truncate';
  211. const pElement = document.createElement('p');
  212. pElement.className = 'text-text-light dark:text-text-dark font-aktiv-grotesk mis-1';
  213. pElement.textContent = expectedTextContent;
  214. textSpan.appendChild(pElement);
  215. newLink.appendChild(textSpan);
  216.  
  217. requestAnimationFrame(() => {
  218. const currentTargetDiv = document.querySelector(targetDivSelector);
  219. if (currentTargetDiv && !document.getElementById(multiVersionLinkId)) {
  220. currentTargetDiv.insertBefore(newLink, currentTargetDiv.firstChild);
  221. console.log(`已為 ${bookNameToDisplay} ${chapter} 加入內嵌連結。`);
  222. }
  223. });
  224. }
  225. } else {
  226. // 非單節經文頁面,檢查敢係歸章个頁面
  227. const chapterMatch = url.match(chapterPageRegex);
  228. if (chapterMatch) {
  229. // 檢查 BOOK.CHAPTER 後面个部分,確保毋係數字 (代表經節)
  230. const pathPartAfterChapterMatch = url.substring(chapterMatch.index + chapterMatch[0].length);
  231. const isTrueChapterPage = !pathPartAfterChapterMatch.startsWith('.') || isNaN(parseInt(pathPartAfterChapterMatch.substring(1).split('.')[0]));
  232.  
  233. if (isTrueChapterPage) {
  234. // 係歸章个頁面
  235. const book = chapterMatch[1];
  236. const chapter = chapterMatch[2];
  237.  
  238. // 移除可能存在个內嵌連結
  239. if (existingInlineLink) {
  240. console.log('章節頁面,移除內嵌連結。');
  241. existingInlineLink.remove();
  242. }
  243. // 加入或更新浮動撳鈕
  244. addOrUpdateFloatingChapterButton(book, chapter, floatingButtonId);
  245. } else {
  246. // 雖然符合 chapterPageRegex,但其實係單節經文頁面 (例如 /PSA.23.1)
  247. // 這情況照理愛由 singleVerseMatch 處理,這係一個額外个防護
  248. if (existingInlineLink) existingInlineLink.remove();
  249. if (existingFloatingButton) existingFloatingButton.remove();
  250. }
  251. } else {
  252. // 非單節經文頁面,也非歸章个頁面 (例如首頁)
  253. if (existingInlineLink) {
  254. console.log('非經文頁面,移除內嵌連結。');
  255. existingInlineLink.remove();
  256. }
  257. if (existingFloatingButton) {
  258. console.log('非經文頁面,移除浮動章節連結。');
  259. existingFloatingButton.remove();
  260. }
  261. }
  262. }
  263. }
  264.  
  265. function addOrUpdateFloatingChapterButton(book, chapter, buttonId) {
  266. const bookNameToDisplay = getBookDisplayName(book);
  267. let button = document.getElementById(buttonId);
  268. const expectedHref = `https://aiuanyu.github.io/6BibleVersions/?book=${book}&chapter=${chapter}`;
  269. const expectedText = "4 語 6 版"; // 撳鈕文字
  270.  
  271. if (button) {
  272. // 浮動撳鈕已存在,檢查並更新
  273. let updated = false;
  274. if (button.href !== expectedHref) {
  275. button.href = expectedHref;
  276. updated = true;
  277. }
  278. if (button.textContent !== expectedText) {
  279. button.textContent = expectedText;
  280. updated = true;
  281. }
  282. // 檢查樣式,確保佢還係浮動个 (雖然較少機會分改忒)
  283. if (button.style.position !== 'fixed') {
  284. button.style.position = 'fixed';
  285. updated = true;
  286. }
  287. if (updated) console.log(`浮動章節連結已更新: ${bookNameToDisplay} ${chapter}`);
  288. } else {
  289. // 浮動撳鈕毋存在,建立佢
  290. button = document.createElement('a');
  291. button.id = buttonId;
  292. button.href = expectedHref;
  293. button.textContent = expectedText;
  294. button.target = '_blank';
  295. button.rel = 'noopener noreferrer';
  296. button.classList.add('custom-floating-bible-link'); // 加一個 class 方便未來調整
  297.  
  298. // 設定浮動樣式
  299. button.style.position = 'fixed';
  300. button.style.top = '80px'; // 考慮到 bible.com 本身个頂部 header
  301. button.style.right = '20px';
  302. button.style.zIndex = '10000'; // 確保在最上層
  303. button.style.padding = '8px 12px';
  304. button.style.backgroundColor = 'rgba(90, 90, 90, 0.85)'; // 深灰色半透明背景
  305. button.style.color = 'white';
  306. button.style.textDecoration = 'none';
  307. button.style.borderRadius = '5px';
  308. button.style.fontSize = '14px';
  309. button.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)';
  310. button.style.transition = 'background-color 0.3s ease'; // 加一息仔滑鼠移過个效果
  311.  
  312. button.onmouseover = () => { button.style.backgroundColor = 'rgba(0, 0, 0, 0.9)'; };
  313. button.onmouseout = () => { button.style.backgroundColor = 'rgba(90, 90, 90, 0.85)'; };
  314.  
  315.  
  316. document.body.appendChild(button);
  317. console.log(`已為 ${bookNameToDisplay} ${chapter} 加入浮動章節連結。`);
  318. }
  319. }
  320.  
  321. function adjustParallelFontSize(retryAttempt = 0) {
  322. const MAX_RETRIES = 10; // 增加重試次數
  323. const RETRY_DELAY = 1200; // 每次重試之間等 1.2 秒鐘
  324. const MIN_COLUMN_HEIGHT_THRESHOLD = 50; // px, 用來判斷內容敢有顯示出來个基本高度
  325.  
  326. try { // try...catch 包住整個函數个內容
  327. const params = new URLSearchParams(window.location.search);
  328. const parallelVersionId = params.get('parallel');
  329.  
  330. if (!parallelVersionId) {
  331. console.log('網址中無尋到並列版本 ID,跳過字體調整。');
  332. return;
  333. }
  334.  
  335. // 取得左欄主要版本个 ID
  336. const pathSegments = window.location.pathname.match(/\/bible\/(\d+)\//);
  337. if (!pathSegments || !pathSegments[1]) {
  338. console.log('無法從路徑中提取主要版本 ID,跳過字體調整。');
  339. return;
  340. }
  341. const mainVersionId = pathSegments[1];
  342.  
  343. const leftDataVidSelector = `[data-vid="${mainVersionId}"]`;
  344. const rightDataVidSelector = `[data-vid="${parallelVersionId}"]`;
  345.  
  346. // 找出並列閱讀个主要容器 (根據先前个 HTML 結構)
  347. const parallelContainer = document.querySelector('div.grid.md\\:grid-cols-2, div.grid.grid-cols-1.md\\:grid-cols-2');
  348. if (!parallelContainer) {
  349. console.log('並列容器 (例如 div.grid.md:grid-cols-2) 未尋到。');
  350. return;
  351. }
  352.  
  353. const columns = Array.from(parallelContainer.children).filter(el => getComputedStyle(el).display !== 'none');
  354. if (columns.length < 2) {
  355. console.log('在並列容器中尋到少於兩个可見欄位。');
  356. return;
  357. }
  358.  
  359. const leftColumnEl = columns[0];
  360. const rightColumnEl = columns[1];
  361.  
  362. const leftVersionDiv = leftColumnEl.querySelector(leftDataVidSelector);
  363. const rightVersionDiv = rightColumnEl.querySelector(rightDataVidSelector);
  364.  
  365. if (!leftVersionDiv || !rightVersionDiv) {
  366. console.log(`左欄 (${leftDataVidSelector}) 或右欄 (${rightDataVidSelector}) 个內容 div 未尋到。`);
  367. if (retryAttempt < MAX_RETRIES -1) { // 為元素搜尋保留一些重試次數
  368. console.warn(`在 ${RETRY_DELAY}ms 後重試元素搜尋 (嘗試 ${retryAttempt + 1}/${MAX_RETRIES})`);
  369. setTimeout(() => adjustParallelFontSize(retryAttempt + 1), RETRY_DELAY);
  370. } else {
  371. console.error('內容 div 元素搜尋在最大重試次數後失敗。中止字體調整。');
  372. }
  373. return; // 若元素無尋到,愛 return 避免錯誤
  374. }
  375.  
  376. // At this point, elements are found. Now check if they have rendered content.
  377. // Force reflow before measurement
  378. leftVersionDiv.offsetHeight;
  379. rightVersionDiv.offsetHeight; // Ensure reflow before measurement
  380. const currentLeftHeight = leftVersionDiv.offsetHeight;
  381.  
  382. if (currentLeftHeight < MIN_COLUMN_HEIGHT_THRESHOLD && retryAttempt < MAX_RETRIES) { // 若左欄高度無夠
  383. console.warn(`左欄高度 (${currentLeftHeight}px) 低於門檻值 (${MIN_COLUMN_HEIGHT_THRESHOLD}px)。內容可能尚未完全渲染。在 ${RETRY_DELAY}ms 後重試 (嘗試 ${retryAttempt + 1}/${MAX_RETRIES})`);
  384. setTimeout(() => adjustParallelFontSize(retryAttempt + 1), RETRY_DELAY);
  385. return;
  386. }
  387. if (currentLeftHeight < MIN_COLUMN_HEIGHT_THRESHOLD && retryAttempt >= MAX_RETRIES) { // 重試了後還係無夠高
  388. console.error(`左欄高度 (${currentLeftHeight}px) ${MAX_RETRIES} 次重試後仍低於門檻值。中止字體調整。`);
  389. return; // 放棄調整
  390. }
  391.  
  392. console.log('尋到左欄版本 Div:', leftVersionDiv, '尋到右欄版本 Div:', rightVersionDiv);
  393.  
  394. // 使用 requestAnimationFrame 來確保 DOM 操作和測量是在瀏覽器準備好繪製下一幀之前進行
  395. // If we reach here, elements are found and left column has some content.
  396. requestAnimationFrame(() => {
  397. // 開始調整字體
  398. let currentFontSize = 90; // 初始字體大小
  399. rightVersionDiv.style.fontSize = currentFontSize + '%';
  400.  
  401. // The leftHeight from *before* rAF (currentLeftHeight) should be the reference.
  402. let leftHeight = currentLeftHeight;
  403. // Ensure right column also reflows with its new font size
  404. let rightHeight = rightVersionDiv.offsetHeight; // 獲取初始高度
  405.  
  406. console.log(`初始檢查字體 ${currentFontSize}%:右欄高度 ${rightHeight}px,左欄高度 ${leftHeight}px (參考值)`);
  407.  
  408. // 如果初始字體大小就已經讓右邊內容不比左邊長,就不用調整了
  409. if (rightHeight <= leftHeight) {
  410. console.log('初始字體大小 ' + currentFontSize + '% 已足夠或更短。');
  411. return;
  412. }
  413.  
  414. // 如果初始字體大小讓右邊內容比左邊長,就開始縮小字體
  415. // 預設使用最小个測試字體 (50%),假使所有測試過个字體都還係分右邊太長。
  416. let bestFitFontSize = 50;
  417. let foundOptimalAdjustment = false;
  418.  
  419. for (let testSize = currentFontSize - 1; testSize >= 50; testSize--) { // 從比初始值小1%開始,最細到 50%
  420. rightVersionDiv.style.fontSize = testSize + '%';
  421. rightHeight = rightVersionDiv.offsetHeight; // 每次改變字體大小後,重新獲取高度 (強制 reflow)
  422.  
  423. if (rightHeight > leftHeight) {
  424. // 這隻 testSize 還係分右邊太長,繼續試較細个字體。
  425. // 假使這係迴圈最後一次 (testSize == 50) 而且還係太長,
  426. // bestFitFontSize 會維持在 50%。
  427. } else {
  428. // 這隻 testSize 分右邊內容變到毋比左邊長了 (<=)。
  429. // 照你个要求,𠊎等愛用前一隻字體大細 (testSize + 1),
  430. // 因為該隻字體大細會分右邊「略略仔長過左邊」。
  431. bestFitFontSize = testSize + 1;
  432. foundOptimalAdjustment = true;
  433. console.log(`右欄內容在 ${testSize}% 時變短/相等 (高度 ${rightHeight}px)。套用前一個較大个字體 ${bestFitFontSize}%。`);
  434. break; // 尋到臨界點了,跳出迴圈
  435. }
  436. }
  437.  
  438. if (!foundOptimalAdjustment && currentFontSize > 50) {
  439. // 假使迴圈跑完,foundOptimalAdjustment 還係 false,
  440. // 表示從 (currentFontSize - 1) 到 50% 所有字體都還係分右邊太長。
  441. // 在這情況下,bestFitFontSize 已經係 50%。
  442. console.log(`所有測試過个字體 (從 ${currentFontSize - 1}% 50%) 仍使右欄內容過長。使用最小測試字體:50%。`);
  443. }
  444.  
  445. // 迴圈結束後,將字體設定為決定好个大小
  446. rightVersionDiv.style.fontSize = bestFitFontSize + '%';
  447. // 為著準確記錄最終狀態,重新量一次高度
  448. const finalRightHeight = rightVersionDiv.offsetHeight;
  449. console.log('' + rightDataVidSelector + ' 最終調整後字體大小為 ' + bestFitFontSize + '%。最終右欄內容高度:' + finalRightHeight + 'px,左欄內容高度:' + leftHeight + 'px');
  450. });
  451. } catch (error) {
  452. console.error('調整字體大小期間發生錯誤:', error);
  453. }
  454. }
  455. })();