728x90
반응형
■ Javascript textarea code highlighter effects
■ 사용법
- 라이브러리 선언
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.1.0/highlight.min.js"></script>
- CSS
@import url("https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.1.0/styles/github.min.css");
@import url('https://fonts.googleapis.com/css2?family=Nanum+Gothic+Coding:wght@400;700&family=Noto+Sans+KR:wght@100;300;400;500;700;900&display=swap');
/* code highlight css */
#editor-container { position: relative; min-height:50px; max-height:500px; overflow:auto; }
#editor-container #s_script, #highlighting-code { position: absolute; top: 0; left: 0; margin: 0; }
#editor-container #s_script, #highlighting-code { padding: 5px; font-family: 'Nanum Gothic Coding', monospace; font-size: 12px; line-height: 15px; }
#editor-container #s_script { color: transparent; background-color: transparent; z-index: 1; caret-color: red; min-height:50px;
border: 1px solid #ddd; border-radius: 3px; width:100%; }
#highlighting-code { z-index: 0; background:unset; border:0; }
#highlighting-code code { font-family: 'Nanum Gothic Coding', monospace; }
- HTML & Javascript
<div id="editor-container">
<textarea id="s_script" name="s_script" placeholder="설치 스크립트 입력해주시기 바랍니다." spellcheck="false" oninput="update_code(); resize();" onkeydown="if(event.keyCode===9){var v=this.value,s=this.selectionStart,e=this.selectionEnd;this.value=v.substring(0, s)+'\t'+v.substring(e);this.selectionStart=this.selectionEnd=s+1;return false;}"></textarea>
<pre id="highlighting-code" class="hljs"><code></code></pre>
</div>
<script type="text/javascript">
function update_code() {
const result_elem = document.querySelector("#highlighting-code code");
const text = document.querySelector("#s_script").value;
let html = hljs.highlightAuto(text).value;
result_elem.innerHTML = html.replace(new RegExp(" ", "g"), " ");;
}
function resize() {
const editor = document.querySelector('#s_script');
editor.style.height = "20px";
editor.style.height = (editor.scrollHeight + 5)+"px";
const editor_div = document.querySelector('#editor-container');
editor_div.style.height = (editor.scrollHeight + 5)+"px";
}
document.addEventListener("DOMContentLoaded", () => {
update_code();
resize();
});
</script>
728x90
반응형
'Javascript' 카테고리의 다른 글
[Javascript] 인증번호 타이머 (0) | 2022.03.22 |
---|---|
[Javascript] Export HTML to Word Document with JavaScript (0) | 2022.03.18 |
[Javascript] textarea 영역에서 tab key 적용하기 탭키 적용 onkeyup (0) | 2022.03.08 |
[Javascript] sweetAlert (알림팝업창) 사용하기 (사용법, 사용예제) (0) | 2022.03.07 |
[Javascript] Toast 창 토스트 메시지 띄우기 (사라지는 모달창) (0) | 2022.03.04 |