-
기타 문서Javascript 2024. 4. 1. 13:11
Mutation observer
Mutation observer 코드 조각이 DOM에 삽입되면 자동으로 감지하고 강조 표시하는데 사용할 수 있다.
<div contentEditable id="elem">Click and <b>edit</b>, please</div> <script> let observer = new MutationObserver(mutationRecords => { console.log(mutationRecords); // console.log(the changes) }); // observe everything except attributes observer.observe(elem, { childList: true, // observe direct children subtree: true, // and lower descendants too characterDataOldValue: true // pass old data to callback }); </script>
-> contentEditable 속성을 사용하면 해당 div를 편집할 수 있습니다.
Selection and Range
deleteContents : 삭제
extractContents : 추출
cloneContents : 복제
insertNode : 삽입
surroundContents :
removeAllRanges : 삭제
선택하려면 먼저 기존에 있는 선택 항목을 삭제해야한다.
선택 항목이 이미 존재하는 경우 removeAllRanges를 사용해서 비우고 그 다음 범위를 추가한다.
*기존 선택을 대체하는 setBaseAndExtext는 예외.
Selection in form controls
👉🏻 onselect 이벤트를 사용해서 선택을 추적하는 방법
<textarea id="area" style="width:80%;height:60px"> Selecting in this text updates values below. </textarea> <br> From <input id="from" disabled> – To <input id="to" disabled> <script> area.onselect = function() { from.value = area.selectionStart; to.value = area.selectionEnd; }; </script>
👉🏻 커서 깜빡이는 위치에 텍스트 삽입하는 방법
<input id="input" style="width:200px" value="Text Text Text Text Text"> <button id="button">Insert "HELLO" at cursor</button> <script> button.onclick = () => { input.setRangeText("HELLO", input.selectionStart, input.selectionEnd, "end"); input.focus(); }; </script>
👉🏻 선택 불가하도록 만들기 2가지
1)
<style> #elem { user-select: none; } </style> <div>Selectable <div id="elem">Unselectable</div> Selectable</div>
2)
<div>Selectable <div id="elem">Unselectable</div> Selectable</div> <script> elem.onselectstart = () => false; </script>
가장 많이 사용되는 예시 두가지
1. 선택 가져오기
let selection = document.getSelection(); let cloned = /* element to clone the selected nodes to */; // then apply Range methods to selection.getRangeAt(0) // or, like here, to all ranges to support multi-select for (let i = 0; i < selection.rangeCount; i++) { cloned.append(selection.getRangeAt(i).cloneContents()); }
2. 선택 셋팅하기
let selection = document.getSelection(); // directly: selection.setBaseAndExtent(...from...to...); // or we can create a range and: selection.removeAllRanges(); selection.addRange(range);
이벤트 루프 - 끊임 없이 돌아가는 자바스크립트 내 루프
*자바스크립트는 한 번에 하나의 수행만 가능하다 - 싱글스레드
*수행 중에는 화면 랜더링이 동시에 되지 않는다.
자바스크립트 엔진을 활성화하는 태스크에는
1. 외부 스크립트 <script stc="..."> 가 로드될 때, 이 스크립트를 실행하는 것
2. 사용자가 마우스를 움직일 때 이벤트 핸들러를 실행하는 것
3. setTimeout에서 설정한 시간이 다 된 경우, 콜백 함수를 실행하는 것
마이크로태스크 : 프로미스, MutationObserver 콜백 등
매크로태스크 : 이벤트 핸들러 또는 setTimeout 등
-> 마이크로태스크가 매크로태스크보다 우선 순위가 높다. 마이크로태스크가 처리된 후에 매크로태스크가 실행된다.
지연시간이 0인 setTimeout을 사용해서 복잡한 큰 태스크 하나를 여러개로 쪼갤 수 있다.
'Javascript' 카테고리의 다른 글
defer, async (1) 2024.03.29 javascript form 폼 조작 (1) 2024.03.27 Pointer event 포인터 이벤트 (0) 2024.03.21 이벤트 기초 (0) 2024.03.14 자바스크립트 문서 (0) 2024.03.13