Contenteditable和jQuery:避免div

时间:2015-01-24 17:11:24

标签: jquery

当用户在contentEditable div中按Enter键时,它会生成div。我怎样才能避免这种情况并创建p或/和br? (请,只有jQuery)

在这里玩和检查:http://jsfiddle.net/r4gaftj2/

jQuery的:

$('#input').keypress(function(e) {
        if(e.which == 13) { // if press enter
            // alert('You pressed enter!'); //it works

            // it does not work:
            // e.preventDefault();
            // $('#input').append("<br>"); 
            // $(this).html('<br><br>');
        }
});

HTML:

<div id="input" contenteditable="true"> </div>

1 个答案:

答案 0 :(得分:1)

有点复杂但有效。

原生对象有时不需要toString实现并返回nil。这就是为什么你没有任何警觉的原因。请使用console.info代替警报。

$('#input').keypress(function(e) {
    if(e.which == 13) {
        // Get current cursor position
        // This is section object
        var s = window.getSelection();
        // Get range object, this object gives you
        // possibility to add new elements after cursor position.
        var range = s.getRangeAt( 0 );
        e.preventDefault();
        // creating initial br
        var last = document.createElement('br');
        // Initial br
        range.insertNode( last );
        // Parent container (editable node)
        var container = s.focusNode;
        // If cursor is inside text container will be text node, need to pull up.
        if ( container.nodeType != HTMLElement.ELEMENT_NODE )
            container = container.parentNode;
        if ( last == container.children.item( container.children.length-1 ) && last.previousSibling && last.previousSibling.nodeType == HTMLElement.ELEMENT_NODE ) {
            // After BR was other element node so it\s safety to add only one BR.
        } else if ( !last.previousSibling || last.previousSibling.nodeType == HTMLElement.TEXT_NODE || (last.nextElementSibling && last.nextElementSibling.tagName != 'BR') ) {
            // If first node: to see new line need br and something and this can't be text node...
            // If next isn't BR need to create second to see new line (see above)
            last = document.createElement('br');
            range.insertNode( last );
        }
        // Cleanup cursor
        s.removeAllRanges();
        // move cursor after last added node
        range.setStartAfter( last );
        range.setEndAfter( last );
        // set new cursor position
        s.addRange( range );
    }
});