Prevent Chrome from wrapping contents of joined

with a

后端 未结 8 1677
情歌与酒
情歌与酒 2021-02-01 16:00

I have observed an undesirable behaviour in Chrome that occurs when one joins two

\'s by deleting the separation between them. Although the

8条回答
  •  一个人的身影
    2021-02-01 16:18

    The best way I found so far is to listen to DOMNodeInserted and check the tagName. If it is a span, you can remove the tag and but leave the contents. This also keeps the cursor at the correct place.

    function unwrap(el, target) {
        if ( !target ) {
            target = el.parentNode;
        }
        while (el.firstChild) {
            target.appendChild(el.firstChild);
        }
        el.parentNode.removeChild(el);
    }
    
    var AutoFix = true;
    
    document.getElementById('editable')
    .addEventListener('DOMNodeInserted', function(ev) {
        if ( !AutoFix ) {
            return;
        }
        if ( ev.target.tagName=='SPAN' ) {
            unwrap(ev.target);
        }
    });
    

    I've added a boolean 'AutoFix' so you can disable the automatic dom changes when you do need to insert a span, since this event fires on any dom change. E.g. if you have a toolbar that allows the user to insert something like ....

    The code has no side effects in IE or FireFox as far as I can see.

提交回复
热议问题