カーソル位置demoの設定

1894 ワード




    
    
    <style>#edit{height:500px;width:300px;border:1px solid red;}</style>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"/>


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


</code></pre> 
 </div> 
</div>
                            </div>
                        </div>