為tinymce增加placeholder功能


話不多說,先看下要實現的效果,如圖所示,為tinymce增加一個默認提示文字,光標移入,文字消失

 

 

1.  需要借助tinymce的一個插件plugin.js,以下為plugin.js的源碼,可以直接復制到自己的文件夾中

tinymce.PluginManager.add('placeholder', function(editor) {
    editor.on('init', function() {
        let label = new Label;

        onBlur();

        tinymce.DOM.bind(label.el, 'click', onFocus);
        editor.on('focus', onFocus);
        editor.on('blur', onBlur);
        editor.on('change', onBlur);
        editor.on('setContent', onBlur);
        editor.on('keydown', onKeydown);

        function onFocus() {
            if (!editor.settings.readonly === true) {
                label.hide();
            }
            editor.execCommand('mceFocus', false);
        }

        function onBlur() {
            if (editor.getContent() == '') {
                label.show();
            } else {
                label.hide();
            }
        }

        function onKeydown(){
            label.hide();
        }
    });

    let Label = function(){
        let placeholder_text = editor.getElement().getAttribute("placeholder") || editor.settings.placeholder;
        let placeholder_attrs = editor.settings.placeholder_attrs || {style: {position: 'absolute', top:'5px', left:0, color: '#888', padding: '1%', width:'98%', overflow: 'hidden', 'white-space': 'pre-wrap'} };
        let contentAreaContainer = editor.getContentAreaContainer();

        tinymce.DOM.setStyle(contentAreaContainer, 'position', 'relative');

        // Create label el
        this.el = tinymce.DOM.add( contentAreaContainer, editor.settings.placeholder_tag || "label", placeholder_attrs, placeholder_text );
    }

    Label.prototype.hide = function(){
        tinymce.DOM.setStyle( this.el, 'display', 'none' );
    }

    Label.prototype.show = function(){
        tinymce.DOM.setStyle( this.el, 'display', '' );
    }
});

 

 

2. 接下來,在頁面中引入js,以及html,此處的tinymce為一個cdn地址,使用時直接換成你是用的版本就好

 

 

3. 默認的label標簽樣式如下,可以自定義lable樣式

{
  style: {
    position: 'absolute',
    top:'5px',
    left:0,
    color: '#888',
    padding: '1%',
    width:'98%',
    overflow: 'hidden',
    'white-space': 'pre-wrap'
  }
}

 

 

4. 自定義lable樣式

.mce-edit-area {
  label {
    color: #A9A9A9 !important; /* Override text color */
    left: 5px !important; /* Override left positioning */
  }
}

 

結束啦

 

參考文獻:https://github.com/mohan/tinymce-placeholder


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM