div 텍스트 선택 효과 편집 가능

14430 단어 JavaScript
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1">
    <title>demo</title>
    <style type="text/css">
        .edit_container {
            width: 500px;
            height: 30px;
            background: #599fc2;
            padding: 3px;
            border-radius: 3px;
            line-height: 30px;
        }

        .btn {
            margin-top: 20px;
            width: 80px;
            height: 20px;
            background: #599fc2;
            padding: 3px;
            border-radius: 3px;
            line-height: 20px;
            text-align: center;
            cursor: pointer;
        }

        .enable_edit {
            border: 1px dashed #1248dd;
        }
    </style>
</head>

<body>
    <p></p>
    <div class="edit_container" id="test">       ....</div>
    <div class="btn">
            
    </div>

    <script src="jquery-1.11.3.min.js"></script>
    <script>
        $(() => {
            $('.btn').click(() => {
                //        
                $('.edit_container').attr('contenteditable', true)
                //       
                $('.edit_container').addClass('enable_edit')

                //      
                let range = document.createRange();
                range.selectNodeContents($(`.edit_container`)[0]); // document.getElementById('test')
                range.collapse(false);
                let sel = window.getSelection();
                sel.removeAllRanges();
                sel.addRange(range);
            });
            //         
            $('.edit_container').focus(() => {
                var selection = window.getSelection();
                selection.removeAllRanges();
                var range = document.createRange();
                range.selectNodeContents($(`.edit_container`)[0]); //      dom       document.getElementById(id)
                selection.addRange(range);
            });
            //        
            $('.edit_container').blur(() => {
                $('.edit_container').removeAttr('contenteditable')
                $('.edit_container').removeClass('enable_edit')
            });
        });
    </script>
</body>

</html>

좋은 웹페이지 즐겨찾기