div可编辑文本的选中文本效果

<!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>

你可能感兴趣的:(JavaScript)