(→Vector 스킨에서 우측 최근 바뀐 문서 보여주는 상자 만들기: 디자인 대폭 개선한 것 반영했습니다.) |
잔글 (코드 오류 수정) |
||
130번째 줄: | 130번째 줄: | ||
$('.live-recent-content').css({"border":"1px solid grey", 'background':'#eee'}); | $('.live-recent-content').css({"border":"1px solid grey", 'background':'#eee'}); | ||
$('.live-recent-list.docupage>li').css({"border-collapse":"collapse"}); | $('.live-recent-list.docupage>li').css({"border-collapse":"collapse"}); | ||
$('.live-recent-list.docupage>li:nth- | $('.live-recent-list.docupage>li:nth-of-type(odd)').css({"background":"#ddd"}); | ||
$('.live-recent-list.docupage>li:nth- | $('.live-recent-list.docupage>li:nth-of-type(even)').css({"background":"#eee"}); | ||
$('.recent-more').css({"border":"1px solid grey", "width":"180px", "background":"#eee"}); | $('.recent-more').css({"border":"1px solid grey", "width":"180px", "background":"#eee"}); | ||
2020년 8월 14일 (금) 01:06 판
리브레 위키를 비롯한 미디어위키 기반의 위키에서는 사용자 환경설정에서 특정한 기능을 제공하는 사용자 고유의 자바스크립트를 삽입하는 기능을 지원하고 있습니다. 이 문서는 이러한 자바스크립트를 사용하는 방법과 그 예제에 대해 올리는 곳입니다.
사용 방법
특:내사용자문서/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');
$("span#pageuseskin").text("Vector");
var $need_margin = Math.min(Math.max(0, 1510-parseInt(window.innerWidth)),190) //1510픽셀 이상일 때는 여백 0, 최대 190픽셀만 여백 지정
if(parseInt(window.innerWidth)>800){ //본문 내용이 800픽셀 이상일 때에만 최근바뀜 상자가 나타나게... 아래는 HTML 구성
//최근 바뀜 목록 보이기 - 출처 : https://github.com/librewiki/liberty-skin/blob/master/js/live-recent.js
$('#content').css("margin-right", String($need_margin)+'px'); // 800px 이상일 때만 여백 나타나게 지정
$( function () {
$( '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 class="recent-item-background"><span class="recent-item">1</span></li><li class="recent-item-background"><span class="recent-item">2</span></li><li class="recent-item-background"><span class="recent-item">3</span></li><li class="recent-item-background"><span class="recent-item">4</span></li><li class="recent-item-background"><span class="recent-item">5</span></li><li class="recent-item-background"><span class="recent-item">6</span></li><li class="recent-item-background"><span class="recent-item">7</span></li><li class="recent-item-background"><span class="recent-item">8</span></li><li class="recent-item-background"><span class="recent-item">9</span></li><li class="recent-item-background"><span class="recent-item">10</span></li></ul></div><div class="recent-more"><span class="mw-editsection-bracket">[</span><a href="//librewiki.net/wiki/특수:최근바뀜" title="최근바뀜문서">more</a><span class="mw-editsection-bracket">]</div></span></div>' ); //HTML 삽입. <li>개수에 따라 아이템 갯수 조절 가능
//기초 css 지정
$('.libre_recent').css({"position":"fixed","top":"15%","right":"10px"});
$('#libre_recent-tabs').css({"display":"flex", "padding":"3px", "border":"1px solid grey", "width":"180px", "background":"#ddf"});
$('#recenttext').css({"padding":"3px", "flex":"1", "background":"#417ff3", "color":"white", "font-weight":"bold"});
$('#recenttalk').css({"padding":"3px", "flex":"1", "background":"white", "font-weight":"bold"});
$('#recent-list-div').css({"width":"180px", "position":"fixed", "top":"auto", "right":"10px"});
$('.live-recent-list.docupage').css({"display":"block", "list-style-type": "none", "padding": "0", "margin": "0"});
$('.live-recent-content').css({"border":"1px solid grey", 'background':'#eee'});
$('.live-recent-list.docupage>li').css({"border-collapse":"collapse"});
$('.live-recent-list.docupage>li:nth-of-type(odd)').css({"background":"#ddd"});
$('.live-recent-list.docupage>li:nth-of-type(even)').css({"background":"#eee"});
$('.recent-more').css({"border":"1px solid grey", "width":"180px", "background":"#eee"});
//가로폭이 좁으면 content 내용 좁히기.
'use strict';
var articleNamespaces, talkNamespaces, isArticleTab, limit; //변수 지정
articleNamespaces = '0|4|10|12|14|1600|1602'; // 문서 페이지 네임스페이스 번호 지정 가능
talkNamespaces = '1|5|7|9|11|13|15|829|1601|1603|2600'; //토론 페이지 네임스페이스 번호 지정가능
isArticleTab = true; //문서 탭이 초기일 때
limit = $( '#live-recent-list' )[ 0 ].childElementCount; // id가 live-recent-list인 ul의 자식 원소인 li 갯수만큼 추출
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 ) { //10보다 작으면 강제로 십의 자리에 0을 끼운다.
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, //긁어오는 문서 숫자 - limit으로 지정
format: 'json', //json으로 api 긁어오기
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 += '[新]'; //새문서 지정
}
text += item.title;
if ( text.length > 13 ) {
text = text.substr( 0, 13 );
text += '...';
}
//text = text.replace( '[New]', '<span class="new">' + mw.msg( 'liberty-feed-new' ) + ' </span>' ); //미작동하므로 코드 비활성화
line += text;
line += '</a></li>';
return line;
} ).join( '\n' );
$( '#live-recent-list' ).html( html );
})
.catch( function () {} );
}
//isArticleTab 바꿔주기
//클릭 시 표시되는 내용 지정
var rtext=$('#recenttext');
var rtalk=$('#recenttalk');
rtext.click(function(){rtext.css({"background":"#417ff3", "color":"white"}); rtalk.css({"background":"white", "color":"black"}); isArticleTab = true; refreshLiveRecent(); }); //최근문서 배경색 파랗게, 최근문서 내용 보이고 최근토론 내용 숨김
rtalk.click(function(){rtext.css({"background":"white", "color":"black"}); rtalk.css({"background":"#417ff3", "color":"white"}); 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)
);
각주
기초 사용법 | |
---|---|
위키 문법 | |
특수 기능 |