Why Is My Contenteditable caret Jumping to the End in Chrome?

后端 未结 6 1598
攒了一身酷
攒了一身酷 2020-12-10 01:59

Scenario

I have a contenteditable

area, and within this area I may have some
6条回答
  •  既然无缘
    2020-12-10 02:31

    So, I've got a slightly cleaner implementation of your approach, which relies on the input event that is triggered when a contenteditable field is updated. This event is not supported by IE, but it looks like contenteditable is pretty wonky in IE anyways.

    It basically injects elements around every element marked as contenteditable="false". It could probably be done on initial load rather than just on the input event, but I figured you might have ways of injecting more span's to the region, so input should account for this.

    Limitations include some weird behavior surrounding the arrow keys, as you've seen yourself. Mostly what I've seen is that the cursor maintains its proper position when you move backward through the spans, but not when you move forward.

    JSFiddle Link

    Javascript

    $('#main').on('input', function() {
        var first = true;
        $(this).contents().each(function(){
            if ($(this).is('[contenteditable=false]')) {
                $("").insertAfter(this);
                if (first) {
                    $("").insertBefore(this);
                    first = false   
                }
            }
        });
    }).trigger('input');
    

    CSS

    div.main {
        width: 400px;
        height: 250px;
        border: solid 1px black;
    }
    
    div.main span {
        width:40px;
        background-color: red;
        border-radius: 5px;
        color: white;
        cursor: pointer;
    }
    
    i.wrapper {
        font-style: normal;
    }
    

提交回复
热议问题