Placeholder for contenteditable div

后端 未结 12 1582
栀梦
栀梦 2020-12-12 23:18

I have the following: FIDDLE

The placeholder works fine and dandy until you type something, ctrl + A, and delete. If you do that, th

12条回答
  •  北荒
    北荒 (楼主)
    2020-12-12 23:49

    I have this function, and I always use to prevent this kind of things.

    I use my function in this way:

    var notEmpty = {}
    
        notEmpty.selector = ".no-empty-plz"
        notEmpty.event = "focusout"
        notEmpty.nonEmpty = "---"
    
    
        neverEmpty(notEmpty)
    

    And I just add the no-empty-plz to the Elements I that don't want to be empty.

    /**
         * Used to prevent a element have a empty content, made to be used 
    when we want to edit the content directly with the contenteditable=true 
    because when a element is completely empty, it disappears U_U
         * 
         * @param selector
         * @param event
         * @param nonEmpty:
         *        String to be put instead empty
         */
    function neverEmpty(params) {
    
        var element = $(params.selector)
    
    
    
        $(document).on(params.event, params.selector, function() {
    
            var text = $(this).html()
            text = hardTrim(text)
    
            if ($.trim(text)  == "") {
                $(this).html(params.nonEmpty)
            }
        });
    }
    

    params is actually a json, so selector = params.selector as you can see

    And hardTrim is also another fucntion I created is like a trim but includs   and
    ,
    etc

    function hardTrim(text) {
    
        if (!exists(text)) {
            return ""
        }
        text = text.replace(/^\ \;|*/gi, "").replace(/\ \;|$/gi, "").trim();
    
        return text
    }
    

提交回复
热议问题