(→예제: 편집 요약창 아래 편집요약 상용구 입력 버튼 추가하는 자바스크립트 삽입) |
잔글 (→문서 위/아래 버튼: 창 높이에 의존하지 않고 숨김 버튼이 작동하게 스크립트 수정) |
||
75번째 줄: | 75번째 줄: | ||
var $bottomButton = $( '#to-bottom' ); | var $bottomButton = $( '#to-bottom' ); | ||
var height=document.body.scrollHeight; | var height=document.body.scrollHeight; | ||
var hminus= | var hminus=height-window.innerHeight-"100"; | ||
$bottomButton.css( { | $bottomButton.css( { | ||
'font-size':'14pt', | 'font-size':'14pt', |
2020년 8월 13일 (목) 23:41 판
리브레 위키를 비롯한 미디어위키 기반의 위키에서는 사용자 환경설정에서 특정한 기능을 제공하는 사용자 고유의 자바스크립트를 삽입하는 기능을 지원하고 있습니다. 이 문서는 이러한 자바스크립트를 사용하는 방법과 그 예제에 대해 올리는 곳입니다.
사용 방법
특:내사용자문서/common.js에 자신이 원하는 기능을 제공하는 자바스크립트 코드를 넣으면 사용할 수 있습니다.
특정 스킨에만 적용되게 사용자 자바스크립트를 적용할 수도 있습니다. "사용자:(계정 필요)/(스킨 식별자, 기본 스킨의 경우 liberty).js" 문서에 코드를 작성하면 됩니다.
이미 있는 스크립트 파일을 사용하실 때에는 mw.loader.load('//(자바스크립트의 주소)');
를 입력해주시면 됩니다. 단, 미디어위키 문서를 불러오실 때는 ?action=raw&ctype=text/javascript
를 주소 뒤에 붙여주셔야 작동합니다.
유용한 외부 자바스크립트
외부 스크립트를 가져다 쓸 수 있습니다. 다만, 외부에서 자바스크립트를 불러오는 것은 해당 내용이 변경되었을 때 부정적인 영향[1]을 받으실 수 있기 때문에 주의하실 필요가 있습니다.
주석[2]을 이용하면 향후 유지보수가 편해질 수 있습니다.
더 많은 정보는 Wikipedia:Wikipedia:User scripts를 참조하시면 됩니다.
/* 토론 문서에서 편집 시에 서명하지 않을 경우 경고 메시지를 출력하는 스크립트입니다. 한위백 IRTC1015님이 작성 */ mw.loader.load('//ko.wikipedia.org/w/index.php?title=User:IRTC1015/qSig.js&action=raw&ctype=text/javascript');
예제
코드가 상당히 길기에 {{숨김 시작}} 틀을 이용해서 내용을 숨겨주시기 바랍니다. 사용하실 때에는 상자 안에 있는 코드 전체를 복사한 뒤에 사용자 자바스크립트에 붙여넣기 하시면 적용이 됩니다.
문서 위/아래 버튼
화면 왼쪽 아래에 맨 위로 올리거나 맨 아래로 내리는 버튼을 삽입할 수 있습니다.
{{숨김 시작}}이나 {{숨기기}} 등의 기능을 사용할 경우 숨긴 내용을 풀 경우 맨 아래로 내리는 기능이 올바르게 작동하지 않을 수 있습니다.
/* 이 스크립트는 Minecraft Wiki의 Majr의 goToTop.js를 (http://minecraftwiki.net/wiki/User:Majr/goToTop.js/) 리브레 위키의 사용자 Utolee90이 재가공해서 만들었습니다. */ /* 위로 올라가는 버튼을 만듭니다. */ $( function() { 'use strict'; $( 'body' ).append( '<span id="to-top">▲ 위</span>' ); var $topButton = $( '#to-top' ); $topButton.css( { 'font-size' : '14pt', 'background-color' : '#0077ff', 'color': '#FFF', 'position': 'fixed', 'bottom': '-30px', 'left': '4px', 'cursor': 'pointer', 'transition': 'bottom 0.5s', '-webkit-transition': 'bottom 0.5s', 'user-select': 'none', '-webkit-user-select': 'none', '-moz-user-select': 'none', '-ms-user-select': 'none' } ).click( function() { $( 'html, body' ).animate( { scrollTop: 0 }, 'slow' ); } ); /* 위에서 100픽셀 이내에 있으면 위 버튼을 숨깁니다. */ $( window ).scroll( function() { if ( $( window ).scrollTop() > 100 ) { $topButton.css( 'bottom', '4px' ); } else { $topButton.css( 'bottom', '-30px' ); } } ); } ); /* 아래 버튼을 만듭니다. */ $( function() { 'use strict'; $( 'body' ).append( '<span id="to-bottom">▼아래</span>' ); var $bottomButton = $( '#to-bottom' ); var height=document.body.scrollHeight; var hminus=height-window.innerHeight-"100"; $bottomButton.css( { 'font-size':'14pt', 'background-color':'#0077ff', 'color': '#FFF', 'position': 'fixed', 'bottom': '-30px', 'left': '42pt', 'cursor': 'pointer', 'transition': 'bottom 0.5s', '-webkit-transition': 'bottom 0.5s', 'user-select': 'none', '-webkit-user-select': 'none', '-moz-user-select': 'none', '-ms-user-select': 'none' } ).click( function() { $( 'html, body' ).animate( { scrollTop:height}, 'slow' ); } ); /*아래에서 100픽셀 이내이면 아래 버튼을 숨깁니다. */ $( window ).scroll( function() { if ( $( window ).scrollTop () <hminus ) { $bottomButton.css( 'bottom', '4px' ); } else { $bottomButton.css( 'bottom', '-30px' ); } } ); } );
Vector 스킨에서 우측 최근 바뀐 문서 보여주는 상자 만들기
특수:내사용자문서/vector.js에 아래 코드를 삽입할 경우 Vector(벡터) 스킨을 사용할 때 Liberty 스킨의 최근 바뀐 문서를 한눈에 보여주는 상자를 삽입하실 수 있습니다. 현재 디자인이나 코딩 최적화가 부족한 점 양해해주시기 바랍니다. 참조. Liberty 스킨의 최근 바뀜 상자를 만들어주는 live-recent.js 코드를 이용해서 재구성했습니다.
원인 미상의 오류로 인해 특수:내사용자문서/vector.js에 직접 아래 소스를 붙여놓으면 자바스크립트가 제대로 작동하지 않습니다. 하위 문서에 아래 소스를 붙여넣은 뒤 mw.loader.load
명령어를 붙여넣거나 아니면 아래 코드를 특수:내사용자문서/vector.js에 붙여넣으시면 됩니다. 그러면 벡터 스킨을 기본 스킨으로 지정할 경우 최근에 편집한 문서를 보여주는 상자를 띄울 수 있습니다.
mw.loader.load('https://librewiki.net/index.php?title=사용자:Utolee90/recentchange.js&action=raw&ctype=text/javascript');
//최근 바뀜 목록 보이기 - 리버티 스킨의 live-recent.js 참조 : https://github.com/librewiki/liberty-skin/blob/master/js/live-recent.js
//오른쪽 상자 공간을 확보하기 위해서 본문의 오른쪽에 여백을 강제로 늘립니다.
$('#content').css("margin-right", "180px");
$( function () { //일단 body.append 명령어를 이용해 최근 바뀜 HTML 작성
$( 'body' ).append('<div class="libre_recent"><div id="libre_recent-tabs"><div id="recenttext" class="selected">최근 문서</div><div id="recenttalk">최근 토론</div></div><div id = "recent-list-div"><div class="live-recent-content"><ul class="live-recent-list docupage" id="live-recent-list"><li><span class="recent-item">1</span></li><li><span class="recent-item">2</span></li><li><span class="recent-item">3</span></li><li><span class="recent-item">4</span></li><li><span class="recent-item">5</span></li><li><span class="recent-item">6</span></li><li><span class="recent-item">7</span></li><li><span class="recent-item">8</span></li><li><span class="recent-item">9</span></li><li><span class="recent-item">10</span></li></ul></div><span class="recent-more"><span class="mw-editsection-bracket">[</span><a href="//bigforest.miraheze.org/wiki/특수:최근바뀜" title="최근바뀜문서">more</a><span class="mw-editsection-bracket">]</span></span></div>' );
//위의 HTML에 대한 css 제작
$('.libre_recent').css({"position":"fixed","top":"15%","right":"10px"});
$('#libre_recent-tabs').css({"display":"flex", "padding":"3px", "border":"1px solid blue", "width":"180px"});
$('#recenttext').css({"padding":"3px", "flex":"1", "background":"#417ff3"});
$('#recenttalk').css({"padding":"3px", "flex":"1", "background":"white"});
$('#recent-list-div').css({"width":"180px", "position":"fixed", "top":"auto", "right":"10px"});
$('.live-recent-list.docupage').css("display","block");
$('.live-recent-content').css("border","1px solid blue");
$('.live-recent-list li').css({"border":"1px solid grey", "border-collapse":"collapse"});
'use strict';
var articleNamespaces, talkNamespaces, isArticleTab, limit;
articleNamespaces = '0|4|10|12|14|1600|1602'; // 원본과는 달리 .live-recent class가 동작하지 않아서 수동으로 이름공간 번호 지정. 사용자 문서는 제외.
talkNamespaces = '1|5|7|9|11|13|15|829|1601|1603|2600';
isArticleTab = true;
limit = $( '#live-recent-list' )[ 0 ].childElementCount;
function timeFormat( time ) { //시간 출력형태 결정
var aDayAgo, hour, minute, second;
aDayAgo = new Date();
aDayAgo.setDate( aDayAgo.getDate() - 1 );
if ( time < aDayAgo ) {
return ( time.getFullYear() ) + '/' + ( time.getMonth() + 1 ) + '/' + time.getDate();
}
hour = time.getHours();
minute = time.getMinutes();
second = time.getSeconds();
if ( hour < 10 ) {
hour = '0' + hour;
}
if ( minute < 10 ) {
minute = '0' + minute;
}
if ( second < 10 ) {
second = '0' + second;
}
return hour + ':' + minute + ':' + second;
}
function refreshLiveRecent() { // 최근 문서 갱신하기 위한 함수.
var getParameter;
if ( !$( '#live-recent-list' ).length || $( '#live-recent-list' ).is( ':hidden' ) ) {
return;
}
getParameter = {
action: 'query',
list: 'recentchanges',
rcprop: 'title|timestamp',
rcshow: '!bot|!redirect',
rctype: 'edit|new',
rclimit: limit,
format: 'json',
rcnamespace: isArticleTab ? articleNamespaces : talkNamespaces,
rctoponly: true
};
var api = new mw.Api();
api.get( getParameter )
.then( function ( data ) {
var recentChanges, html, time, line, text;
recentChanges = data.query.recentchanges;
html = recentChanges.map( function ( item ) {
time = new Date( item.timestamp );
line = '<li><a class="recent-item" href="' + mw.util.getUrl( item.title ) + '" title="' + item.title + '">[' + timeFormat( time ) + '] ';
text = '';
if ( item.type === 'new' ) {
text += '[New]';
}
text += item.title;
if ( text.length > 13 ) {
text = text.substr( 0, 13 );
text += '...';
}
text = text.replace( '[New]', '[신규]' ); // 자바스크립트 형태로 삽입하면 리브레위키의 미디어위키 이름공간에 지정된 liberty-feed-new 메시지는 사용불가능. 따라서 텍스트를 직접 신규로 대체
line += text;
line += '</a></li>';
return line;
} ).join( '\n' );
$( '#live-recent-list' ).html( html );
})
.catch( function () {} );
}
//클릭 시 표시되는 내용 지정
var rtext=$('#recenttext'); //최근 문서
var rtalk=$('#recenttalk'); //최근 토론
rtext.click(function(){rtext.css("background", "#417ff3"); rtalk.css("background", "white"); isArticleTab = true; refreshLiveRecent(); }); //최근문서 글자 배경색 파랗게, 최근문서 내용 보이고 최근토론 내용 숨김
rtalk.click(function(){rtext.css("background", "white"); rtalk.css("background", "#417ff3"); isArticleTab = false; refreshLiveRecent(); } ); //최근토론 글자 배경색 파랗게, 최근문서 내용 숨기고 최근토론 내용 보임
setInterval( refreshLiveRecent, 5 * 60 * 1000 );
refreshLiveRecent();
} );
편집 요약창 아래 편집요약 상용구 입력 버튼 추가
/* 한국어 위키백과 미디어위키:Gadget-editsummary.js 호출. 사용자:Utolee90/Addbutton.js 참조 */
function esEditSummary() {
if (typeof esEditSummaries === 'undefined') return;
var wgAction = mw.config.get('wgAction');
if (wgAction == 'edit' || wgAction == 'submit') {
var wpSummary = document.getElementById('wpSummary');
if (!wpSummary || (wpSummary.form.wpSection && wpSummary.form.wpSection.value == 'new')) return;
wpSummaryButtons = document.createElement('span');
wpSummaryButtons.id = 'esSummaryButtons';
wpSummary.parentNode.insertBefore(wpSummaryButtons, wpSummary.nextSibling);
for (var i = 0; i < esEditSummaries.length; i++) esAppendButton(i);
}
}
function esAppendButton(id) { // 버튼 추가하는 함수
var btn = document.createElement('esSummaryButton');
btn.appendChild(document.createTextNode(esEditSummaries[id][0]));
btn.title = esEditSummaries[id][2];
btn.onclick = function() {esInsertSummary(esEditSummaries[id][1], esEditSummaries[id][3], esEditSummaries[id][4])};
wpSummaryButtons.appendChild(btn);
}
function esInsertSummary(text, isMinor, clear) {
var wpSummary = document.getElementById('wpSummary');
if (isMinor !== undefined) { $('#wpMinoredit').prop('checked', isMinor, clear); }
if (clear == 1) {
wpSummary.value = text;
return;
}
if (wpSummary.value.indexOf(text) != -1) return ;
if (wpSummary.value.match(/[^,; \/]$/)) wpSummary.value += ',';
if (wpSummary.value.match(/[^ ]$/)) wpSummary.value += ' ';
wpSummary.value += text;
}
jQuery( document ).ready(esEditSummary);
esEditSummaries = new Array(
/*
new Array('버튼 이름', '입력될 편집 요약', '툴팁으로 뜨는 설명(생략 가능)', '사소한 편집 여부(0/1 혹은 true/false, 생략 가능)', '상용구 넣기 전에 요약 지우기(0/1 혹은 true/false, 생략 가능)')
위와 같은 형식으로 새로운 버튼을 추가할 수 있습니다.
마지막 줄을 제외한 줄 끝에 쉼표가 들어가 있는지 확인해 주세요.
*/
// 예시 -
new Array('오타','오타 수정','문서에서 오타를 정정함', 0, 1)
);
각주
기초 사용법 | |
---|---|
위키 문법 | |
특수 기능 |