Prevent line/paragraph breaks in contentEditable

前端 未结 11 473
青春惊慌失措
青春惊慌失措 2020-12-13 17:18

When using contentEditable in Firefox, is there a way to prevent the user from inserting paragraph or line breaks by pressing enter or shift+enter?

11条回答
  •  攒了一身酷
    2020-12-13 17:43

    $("#idContentEditable").keypress(function(e){ return e.which != 13; });
    

    Solution proposed by Kamens doesn't work in Opera, you should attach event to document instead.

    /**
     * Pass false to enable
     */
    var disableEnterKey = function(){
        var disabled = false;
    
        // Keypress event doesn't get fired when assigned to element in Opera
        $(document).keypress(function(e){
            if (disabled) return e.which != 13;
        });                 
    
        return function(flag){
            disabled = (flag !== undefined) ? flag : true;
        }
    }();    
    

提交回复
热议问题