2012-09-04 66 views
6

如何在CKEditor中添加自定義類或ID到文本段落?我想從DB加載可能的類,並將它們寫入到CKE正在加載的列表中。身份證件只會在現場製作。類和ID將被用於諸如將一段文本標記爲腳註或標題。如何在CKEditor中將CSS類和ID添加到段落中?


只是要清楚,我不想使用下拉框,我想補充一點,可用於設計元素後,它已被保存-depending CSS類來改變顯示的樣式文本在哪裏使用。

回答

3

在這裏,你去。這段代碼會將你的段落編號爲後續的id,並且還會爲每個尚未分配的段落添加一個自定義類別。

var idCounter = 0, 
    pClass = 'myCustomClass', 
    pClassRegexp = new RegExp(pClass, 'g'); 

CKEDITOR.replace('editor1', { 
    on: { 
     instanceReady: function() { 
      this.dataProcessor.htmlFilter.addRules({ 
       elements: { 
        p: function(element) { 
         // If there's no class, assing the custom one: 
         if (!element.attributes.class) 
          element.attributes.class = pClass; 

         // It there's some other class, append the custom one: 
         else if (!element.attributes.class.match(pClassRegexp)) 
          element.attributes.class += ' ' + pClass; 

         // Add the subsequent id: 
         if (!element.attributes.id) 
          element.attributes.id = 'paragraph_' + ++idCounter; 
        } 
       } 
      }); 
     } 
    } 
}); 
+0

'class'是JS的保留字,你應該在引號包裹:'element.attributes ['class']' – fncomp

+0

我說我的問題有點不對:PI想讓編輯器的當前用戶決定哪個ID和哪個類給某個元素。無論如何,感謝您的意見。我的賞金是關注這個問題,所以我把它授予唯一的注意力:) – Nenotlep

+0

這正是我一直在尋找:)只需少量修改(我需要一些SHA1 ID)它應該完美無缺地工作。非常感謝! :) –

0

我已經走了四周,做這樣的事情(我使用CKEDITOR 4.4.7):

editor.addCommand('colSm1', { 
    exec: function (editor) { 
    var $element = editor.elementPath().block; 

    if ($element.getAttribute('class') == null) { 
     $element.addClass('col-sm-1'); 
    } 
});