MediaWiki:Gadget-SelectionCounter.js
MediaWiki界面页面
更多操作
注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。
- Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5或Ctrl-R(Mac为⌘-R)
- Google Chrome:按Ctrl-Shift-R(Mac为⌘-Shift-R)
- Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5。
/* ================================================================
MediaWiki Gadget: SelectionCounter
功能:
- 选中文本时显示字数统计
- 与 RightToolbar 风格一致
================================================================= */
mw.loader.using(['mediawiki.util']).then(function () {
if (window.SelectionCounterLoaded) {
return;
}
window.SelectionCounterLoaded = true;
$(function () {
var $counter = $('#mw-selection-counter');
if (!$counter.length) {
$counter = $('<div id="mw-selection-counter" class="mw-selection-counter" role="status" aria-live="polite"></div>')
.hide()
.appendTo('body');
}
var rafId = null;
function getSelectionText() {
var selection = window.getSelection();
if (!selection || selection.isCollapsed) {
return '';
}
return String(selection).trim();
}
function updateCounter() {
rafId = null;
var active = document.activeElement;
if (active && (active.tagName === 'INPUT' || active.tagName === 'TEXTAREA' || active.isContentEditable)) {
$counter.hide();
return;
}
var text = getSelectionText();
if (!text) {
$counter.hide();
return;
}
var count = Array.from(text).length;
$counter.text('已选 ' + count + ' 字').show();
}
function scheduleUpdate() {
if (rafId) {
return;
}
rafId = window.requestAnimationFrame(updateCounter);
}
document.addEventListener('selectionchange', scheduleUpdate);
document.addEventListener('mouseup', scheduleUpdate);
document.addEventListener('keyup', scheduleUpdate);
document.addEventListener('touchend', scheduleUpdate, { passive: true });
});
});