MediaWiki:Common.js
外观
注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。
- Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5或Ctrl-R(Mac为⌘-R)
- Google Chrome:按Ctrl-Shift-R(Mac为⌘-Shift-R)
- Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5。
/* 这里的任何JavaScript将为所有用户在每次页面加载时加载。 */
/* 灰白里程有尽矿井计算器 */
( function () {
'use strict';
var state = { x: 0 };
function toJS( raw ) {
var s = String( raw ).trim();
s = s.replace( /×/g, '*' ).replace( /÷/g, '/' )
.replace( /(/g, '(' ).replace( /)/g, ')' )
.replace( /[-—–−]/g, '-' ).replace( /\s+/g, '' );
s = s.replace( /(\d)(x)/g, '$1*$2' ).replace( /(x)(\d)/g, '$1*$2' )
.replace( /(\d)\(/g, '$1*(' ).replace( /\)(\d)/g, ')*$1' )
.replace( /\)(x)/g, ')*$1' ).replace( /(x)\(/g, '$1*(' );
s = s.replace( /⌊([^⌋]*)⌋/g, function ( m, inner ) {
return 'Math.floor(' + inner + ')';
} );
return s;
}
function evalExpr( raw, x ) {
try {
var fn = new Function( 'x', 'return (' + toJS( raw ) + ');' );
var v = fn( x );
if ( typeof v !== 'number' || !isFinite( v ) ) return null;
return Math.round( v );
} catch ( e ) { return null; }
}
function sanitizeX( v ) {
var n = Math.floor( Number( v ) );
if ( !isFinite( n ) || n < 0 ) n = 0;
return n;
}
function eachNode( sel, fn ) {
Array.prototype.forEach.call( document.querySelectorAll( sel ), fn );
}
function initOutputs() {
eachNode( '.calc-out', function ( el ) {
if ( el.__expr === undefined ) el.__expr = el.textContent.trim();
} );
}
function renderOutputs() {
eachNode( '.calc-out', function ( el ) {
if ( el.__expr === undefined ) el.__expr = el.textContent.trim();
var v = evalExpr( el.__expr, state.x );
if ( v !== null ) el.textContent = String( v );
} );
}
function buildInput( box, xValue ) {
if ( box.querySelector( '.calc-input' ) ) return;
var labelText = box.textContent.trim() || '数量 x';
box.textContent = '';
var label = document.createElement( 'label' );
label.className = 'calc-label';
label.appendChild( document.createTextNode( labelText.replace( /[::]\s*$/, '' ) + ':' ) );
var input = document.createElement( 'input' );
input.type = 'number';
input.min = '0';
input.step = '1';
input.value = String( xValue );
input.className = 'calc-input';
input.setAttribute( 'inputmode', 'numeric' );
input.setAttribute( 'aria-label', labelText );
input.addEventListener( 'input', function () {
state.x = sanitizeX( input.value );
renderOutputs();
} );
input.addEventListener( 'blur', function () {
state.x = sanitizeX( input.value );
input.value = String( state.x );
renderOutputs();
} );
label.appendChild( input );
box.appendChild( label );
}
function initBoxes() {
eachNode( '.calc-box', function ( box ) { buildInput( box, state.x ); } );
}
function start() { initOutputs(); initBoxes(); renderOutputs(); }
if ( document.readyState === 'loading' ) {
document.addEventListener( 'DOMContentLoaded', start );
} else { start(); }
} )();