마우스로 드래그해서 선택한 텍스트 가져오기

script 2009. 9. 4. 15:23
어떤 사이트들에서는 페이지의 텍스트를 드래그해서 선택한 후 바로 검색을 할 수 있게 만든 기능들이 있다.
그래서 그 기능의 핵심인 선택한 텍스트를 가져오는 스크립트를 만들어 보았다.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <style type="text/css">
            #console { width: 300px; height: 20px; border: 1px solid #ccc; }
        </style>
        <script type="text/javascript">
            function selectText() {
                var selectionText = "";
                if (document.getSelection) {
                    selectionText = document.getSelection();
                } else if (document.selection) {
                    selectionText = document.selection.createRange().text;
                }
                return selectionText;
            }
           
            document.onmouseup = function() {
                document.getElementById("console").innerHTML = selectText();
            }
        </script>
    </head>
    
    <body>
        <p>abcdefghijklmnopqrstuvwxyz</p>
        <p>마우스로 드래그해서 선택한 글 나오기</p>
        <div id="console"></div>
    </body>
</html>



데모


abcdefghijklmnopqrstuvwxyz

마우스로 드래그해서 선택한 글 나오기

: