Computer >> 컴퓨터 >  >> 프로그래밍 >> JavaScript

JavaScript로 사용자가 선택한 텍스트 내용을 가져오는 방법

웹 페이지에서 사용자가 마우스로 드래그하여 선택한 텍스트를 자바스크립트로 가져와야 하는 경우가 종종 있습니다. 이때 window.getSelection() 메서드를 사용하면 현재 선택된 텍스트 정보에 손쉽게 접근할 수 있으며, toString() 메서드를 함께 호출하면 순수한 문자열 형태로 변환할 수 있습니다.

예제 코드

다음은 JavaScript를 사용하여 사용자가 선택한 텍스트 내용을 가져오고, 버튼 클릭 시 화면에 출력하는 전체 코드입니다.

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result,.sample {
      font-size: 20px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Retrieve the text contents of the user selection</h1>
<div style="color: green;" class="result">
Here is some text inside the div
</div>
<div class="sample"></div>
<button class="Btn">SELECT</button>
<h3>Click on the above button to display the text selected by the user</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let sampleEle = document.querySelector(".sample");
   BtnEle.addEventListener("click", () => {
      sampleEle.innerHTML = window.getSelection().toString();
   });
</script>
</body>
</html>

코드 설명

  • document.querySelector()를 사용해 초록색 텍스트가 담긴 .result 영역, 결과를 표시할 .sample 영역, 그리고 .Btn 버튼 요소를 각각 참조합니다.
  • 버튼에 click 이벤트 리스너를 등록하고, 버튼이 클릭되면 window.getSelection().toString()으로 사용자가 드래그해 선택한 텍스트를 문자열로 가져옵니다.
  • 가져온 텍스트는 innerHTML을 통해 .sample 영역에 그대로 출력됩니다.

실행 결과

위 코드를 실행하면 다음과 같은 화면이 나타납니다.

JavaScript로 사용자가 선택한 텍스트 내용을 가져오는 방법

초록색 영역의 일부 텍스트를 마우스로 드래그하여 선택한 뒤 'SELECT' 버튼을 클릭하면, 선택된 텍스트가 아래 영역에 출력됩니다.

JavaScript로 사용자가 선택한 텍스트 내용을 가져오는 방법

이처럼 window.getSelection() 메서드를 활용하면 별도의 라이브러리 없이도 사용자가 선택한 텍스트를 간단하게 추출할 수 있습니다. 텍스트 하이라이트 기능, 인용 기능, 검색 기능 등을 구현할 때 유용하게 활용할 수 있습니다.