开发者

jquery contenteditable enter "How do I trigger shift-enter when someone presses enter?"

When pressi开发者_如何学Cng enter in contenteditable in chrome, a div is inserted. This interferes with my markup, I need it to be a br.

I know that shift-enter is a br. What is the best way to solve the problem?

Thanks.

Reformulating the question: How do I trigger shift-enter when someone presses enter?

I've tried writing something like this:

$(document).keyup(function hotkeys(e) { 
    if (e.which == 13)
    {
        e = jQuery.Event("keydown")
        e.which = 16;
        $(document).trigger(e);
        e.which = 13;
        $(document).trigger(e);
        alert("trigger");
    }
});

It doesn't work.

Thanks.


Assuming rangy.js,

$('#myeditelement').on('keydown', function(ev){
    if (ev.which === 13) { insertNewLine(ev) }
})

then,

function insertNewLine(ev){
    var nodeA, nodeB, sel, range

    if (ev.stopPropagation) { ev.stopPropagation() }
    if (ev.preventDefault) { ev.preventDefault() }

    sel = rangy.getSelection()
    range = sel.getRangeAt(0)

    range.deleteContents()
    nodeA = document.createElement('br')
    range.insertNode(nodeA)
    range.setStartAfter(nodeA)
    nodeB = document.createElement('span')
    range.insertNode(nodeB)
    range.selectNodeContents(nodeB)
    sel.removeAllRanges()
    sel.addRange(range)
    sel.collapseToEnd()
  }

Tested in Chrome, Opera, Edge as of November 2017.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜