我使用的是微型mce,但我发现它为任何应用样式的内容添加了多个具有内联样式的跨度。内联样式不符合W3c,因此必须避免内联css。在微型mce中编辑内容时,是否可以动态创建css类并将其应用于所选内容?
发布于 2010-07-09 15:09:37
是的,这是可能的,但这需要我付出一些努力。需要做的是将类写入编辑器iframe的头部。以下是一些示例代码,它们应该适用于IE、FF、Safari,并为您指明正确的方向:
fonturl = "http://myfonts.com/arial.ttf"
csstext_to_add = '@font-face {font-family: "ownfont";src: url("'+fonturl+'");}'; // example
iframe_id = ed.id;
with(document.getElementById(iframe_id).contentWindow){
var h=document.getElementsByTagName("head");
if (!h.length) {
return;
}
var newStyleSheet=document.createElement("style");
newStyleSheet.type="text/css";
h[0].appendChild(newStyleSheet);
try{
if (typeof newStyleSheet.styleSheet !== "undefined") {
newStyleSheet.styleSheet.cssText = csstext_to_add;
}
else {
newStyleSheet.appendChild(document.createTextNode(csstext_to_add));
newStyleSheet.innerHTML=csstext_to_add;
}
}
catch(e){}
}也可以将class as选项添加到下拉列表中(这需要一些努力)。
发布于 2011-12-16 01:14:43
Thariama的回答是完美的。我在一些页面中使用了tinyMCE jQuery连接器,并且在页面上有多个tinyMCE实例。我做了一些修改,但本质上是一样的。我已经在页面上创建了一个文本区域字段,人们可以提供自己的CSS。此外,我还需要动态更改一些CSS规则……
// function to change tinyMCE css on the fly
function checkCustomCSS() {
var $css = $('#page_css'),
newcss;
if ($css.val().length > 0) {
// since front end, we are wrapping their HTML in a wrapper and
// the tinyMCE edit iFrame is just using <body>, we need to change
// some rules so they can see the changes
newcss = $css.val().replace('#content_wrapper', 'body');
// loop through each tinyMCE editor and apply the code changes
// You could check the editor.id to make sure that the correct
// editor gets the appropriate changes.
$.each(tinyMCE.editors, function() {
var $this = $(this),
editorID = $this[0].id,
$ifrm = $('#' + editorID+ '_ifr'),
cwin, head, sheet;
if ($ifrm.length > 0 /* && editorID === 'OUR_EDITOR_ID_NAME' */) {
cwin = $ifrm[0].contentWindow;
head = cwin.document.getElementsByTagName("head");
if (!head.length) {
return;
}
sheet = cwin.document.createElement("style");
sheet.type = "text/css";
head[0].appendChild(sheet);
try {
if (typeof sheet.styleSheet !== "undefined") {
sheet.styleSheet.cssText = newcss;
} else {
sheet.appendChild(cwin.document.createTextNode(newcss));
sheet.innerHTML = newcss;
}
} catch (e) {}
}
});
}
}然后,在tinyMCE初始化调用中,我添加了onInit调用来设置对#page_css的更改,如下所示:
oninit: function() {
$('#page_css').on('change', function() {
checkCustomCSS();
});
}就像一种护身符。
https://stackoverflow.com/questions/3210394
复制相似问题