2015-04-23 51 views
4

我對CKEDITOR API還不是很熟悉,現在我陷入了困境,試圖找到在CKEDITOR可編輯區域內創建佔位符的方式。佔位符的預期行爲 - 消失在用戶與它交互時,允許編輯內容。CKEDITOR中的文本佔位符(角度上下文)

我知道已經有一個佔位符插件(http://ckeditor.com/addon/placeholder),但其行爲不是我正在尋找的。

更具體地說,問題是:是否可以訂閱CKEDITOR內特定元素上的某些事件?

在角度方面我能夠編譯我的HTML被傳遞給CKEDITOR NG-模型

$scope.html = $compile('<div><span text-placeholder >Placeholder</span></div>')($scope).html(); 

但我無法嘗試設置點擊指令的內部事件前的狀態:

.directive('textPlaceholder', [ function() { 
    return { 
     restrict: 'A', 
     link: function ($scope, $element) { 
      //THIS DOES NOT WORK UNFORTUNATELY 
      $element.on('click', function() { 
       console.log('clicked'); 
      }) 
     } 
    } 
}]) 

有什麼想法?

UPDATE:現在,我想出瞭解決方案,以實現簡單的插件,然後引用它在CKEDITOR配置:

(function() { 
CKEDITOR.plugins.add('text-placeholder', { 
    init: function (editor) { 

     editor.on('key', function (evt) { 
      var el = $(CKEDITOR.instances.editor1.getSelection().getNative().baseNode.parentElement); 
      if (el.hasClass('text-placeholder')) { 
       el.remove(); 
      } 
     }); 

    } 
}); 

})();

看起來很醜。任何反饋意見。

回答

2

這似乎是一個最終的解決方案:當用戶聚焦它的可編輯區域

更新的內部

CKEDITOR.plugins.add('text-placeholder', { 
    init: function (editor) { 
     editor.on('contentDom', function() { 
      var editable = editor.editable(); 
      editable.attachListener(editable, 'click', function (event) { 
       var $placeholder = $(event.data.$.target).closest('.text-placeholder'); 
       if ($placeholder.length > 0) { 
        var selection = editor.getSelection(); 
        selection.selectElement(selection.getStartElement()); 
       } 
      }); 
     }); 
    } 
}); 

這適用元素與「文本佔位符」類選擇: See example

2

你鼓勵我自己寫一個,以上面的例子爲出發點。在我的用例中,我想從編輯器的數據佔位符的屬性中取得佔位符文本,並將其顯示在編輯器中。當編輯器獲得焦點時,佔位符文本消失。當編輯器模糊 - 如果沒有輸入用戶內容 - 佔位符文本再次顯示。此外,我設置了數據佔位符顯示屬性,以便我可以使用CSS來使佔位符文本變灰。這是我的代碼:

CKEDITOR.plugins.add('text-placeholder', { 
    init: function (editor) { 
    var placeholder = editor.element.getAttribute('data-placeholder'); 
    editor.on('contentDom', function() { 
     if (placeholder) { 
     editor.setData(placeholder); 
     editor.element.setAttribute('data-placeholder-showing', true); 
     } 
    }); 
    editor.on('focus', function() { 
     if (editor.getData() === placeholder) { 
     editor.element.setAttribute('data-placeholder-showing', false); 
     editor.setData(''); 
     } 
    }); 
    editor.on('blur', function() { 
     if (placeholder && editor.getData().length === 0) { 
     editor.element.setAttribute('data-placeholder-showing', true); 
     editor.setData(placeholder); 
     } 
    }); 
    } 
});