Tinymce html5 placeholder by reading attribute from textarea

前端 未结 8 605
北恋
北恋 2020-12-31 19:41

For standard textareas I use this plugin to create a placeholder. How can I extend tinymce so that this works in this way also.

E.g the default value is read from the

8条回答
  •  醉酒成梦
    2020-12-31 20:27

    For tinymce 4 I had problems with the events where ed.onInit was not defined. tinymce 4 uses ed.on('event' , callback) instead. Here is my implementation. I also used focus instead of mousedown as the event to listen for when clearing the editor because mousdown wasn't working for some reason.

    setup :  function(ed) {
    
            // Set placeholder
            var tinymce_placeholder = $('#'+ed.id);
            var attr = tinymce_placeholder.attr('placeholder');
    
            // For some browsers, `attr` is undefined; for others,
            // `attr` is false.  Check for both.
            if (typeof attr !== 'undefined' && attr !== false) {
                var is_default = false;
    
                ed.on('init' , function(ed) {
                    // get the current content
                    var cont = ed.target.getContent();
    
                    // If its empty and we have a placeholder set the value
                    if(cont.length == 0){
                        ed.target.setContent(tinymce_placeholder.attr("placeholder"));
    
                        // Get updated content
                        cont = tinymce_placeholder.attr("placeholder");
                    }
    
                    // convert to plain text and compare strings
                    is_default = (cont == tinymce_placeholder.attr("placeholder"));
    
                    // nothing to do
                    if (!is_default){
                        return;
                    }
                });
    
                ed.on('focus', function(ed,e) {
                    // replace the default content on focus if the same as original placeholder
                    if (is_default){
                        ed.target.setContent('');
                    }
                });
            }
        }
    

    hope this helps for anyone who had problems with the other answers

提交回复
热议问题