MediaWiki:Gadget-AudioText.js
外观
注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。
- Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5或Ctrl-R(Mac为⌘-R)
- Google Chrome:按Ctrl-Shift-R(Mac为⌘-Shift-R)
- Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5。
// MediaWiki:Gadget-AudioText.js (function() { const audioUrlCache = new Map(); // 播放音频核心逻辑 function handlePlay(element) { const audioFile = element.dataset.audioFile; // 优先使用缓存 if (audioUrlCache.has(audioFile)) { new Audio(audioUrlCache.get(audioFile)).play(); return; } // 通过API获取真实URL const apiUrl = mw.util.wikiScript('api') + '?action=query&titles=' + encodeURIComponent(audioFile) + '&prop=imageinfo&iiprop=url&format=json'; fetch(apiUrl) .then(response => response.json()) .then(data => { const pages = data.query.pages; const pageId = Object.keys(pages)[0]; const audioUrl = pages[pageId].imageinfo[0].url; audioUrlCache.set(audioFile, audioUrl); new Audio(audioUrl).play(); }); } // 初始化事件绑定 function initAudioTriggers() { document.querySelectorAll('.audio-trigger').forEach(element => { if (element._audioBound) return; element._audioBound = true; // 统一事件处理器(不阻止冒泡和默认行为) const handler = (event) => { handlePlay(element); // 不调用 event.stopPropagation() 或 event.preventDefault() }; // 同时绑定touch和click(passive模式提升移动端性能) element.addEventListener('touchstart', handler, { passive: true }); element.addEventListener('click', handler); }); } // 页面加载时初始化 mw.hook('wikipage.content').add(initAudioTriggers); mw.loader.using('mediawiki.api').then(initAudioTriggers); })();