네이티브 자바스크립트 Selection API 사용 블럭 지정된 텍스트 가져오기
페이지 정보
본문
$(function(e) {
// 블럭 지정된 텍스트 가져오기
$(document).on('mouseup', function(e) {
var selection = window.getSelection();
var selectedText = $.trim( selection.toString() ); // 선택된 텍스트를 문자열로 반환
if (selectedText.length > 0) {
console.log('블럭 지정된 내용 : ' + selectedText);
}
});
// 블럭 지정된 텍스트 강조(Highlight)하기
$(document).on('mouseup', function(e) {
var selection = window.getSelection();
var selectedText = $.trim( selection.toString() );
if (selectedText.length > 0) {
// 선택된 영역을 span 태그로 감싸고 하이라이트 클래스 적용
var range = selection.getRangeAt(0);
var span = document.createElement('span');
span.style.backgroundColor = 'yellow';
span.className = 'highlighted';
range.surroundContents(span);
selection.removeAllRanges();// 선택 해제
}
});
// 특정 영역 내에서만 블럭 지정 감지
$(document).on('mouseup', function(e){
var selection = window.getSelection();
var selectedText = $.trim( selection.toString() ); // 선택된 텍스트를 문자열로 반환
var content_area = document.querySelector('.content_area');
if (selectedText.length > 0) {
// selection.anchorNode는 사용자가 드래그를 시작한 노드
if (content_area.contains(selection.anchorNode)) {
console.log('블럭 지정된 내용 : ' + selectedText);
}
}
});
});
추천
0
비추천
0
- 이전글 Summernote에서 전체 화면(Fullscreen) 모드 적용 26.02.16
- 다음글 summernote 에디터에서 특정객체 hover시 tooltip 변경하기 26.01.30
