設置光標位置demo

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <style>#edit{height:500px;width:300px;border:1px solid red;}</style>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
</head>
<body>
    <div id="edit" class="test" contenteditable>
        <p>這裏就是我需要變動的位置了</p>
    </div>
    <button id="positionCursor">點擊定位光標</button>
    <script>
        document.getElementById('edit').focus();
        var positionCursor = document.getElementById('positionCursor');
        function positionCaret(textNode, position) {
            if (textNode.setSelectionRange) {
                textNode.setSelectionRange(position, position);
            } else if (textNode.createTextRange) {
                var range = textNode.createTextRange()
                range.moveStart("character", -textLength)
                range.moveEnd("character", -textLength)
                range.moveStart("character", position)
                range.moveEnd("character", 0)
                range.select();
            } else {
                var newRange = document.createRange();
                newRange.setStart(textNode, position);
                newRange.collapse(true);
    
                var selection = window.getSelection();
                selection.removeAllRanges();
                selection.addRange(newRange);
            }
        }
        positionCursor.addEventListener('click', function() {
            let p = document.getElementById('edit').getElementsByTagName('p')[0].childNodes[0];
            // 這裏只是要寫一個demo, 所以直接將光標要落的位置設置爲2
            positionCaret(p, 2);
        })
    </script>
</body>
</html>
發佈了95 篇原創文章 · 獲贊 137 · 訪問量 31萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章