Cómo cambiar el tamaño automático TinyMCE?


Tengo un TinyMCE que se establece sobre un área de texto, y quiero que este área de editor ocupe todo el espacio de su div padre, todo el tiempo.

Tengo una función JS que obtiene el espacio actual y establece el área de texto.estilo.altura a ella, pero cuando me permite TinyMCE parece dejar de funcionar.

Además, el área de texto tiene un ancho: 100%; no cambia de tamaño por renderizado HTML cuando también está usando TinyMCE.

¿Alguna idea?

Author: igorsantos07, 2009-11-25

11 answers

Hoy en día, debe usar el complemento autoresize que viene con TinyMCE. Tendrás que llamar a TinyMCE así (versión jQuery):

$('.tinymce').tinymce({
  theme : 'advanced',
  plugins : 'autoresize',
  width: '100%',
  height: 400,
  autoresize_min_height: 400,
  autoresize_max_height: 800,
});

Hice la experiencia, que puede ser útil llamar manualmente al redimensionamiento en el init_instance_callback para proporcionar la altura correcta en init. Agregue este parámetro a las opciones pasadas, si necesita esto:

init_instance_callback: function (inst) { inst.execCommand('mceAutoResize'); }
 47
Author: bfncs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2012-09-12 07:00:13

El punto es que TinyMCE genera un iframe en el lugar del área de texto, con este ID: originalID+"_ifr", y una tabla originalID+"_tbl" para mantener los controles y el área del editor.

Para hacer ancho de fluido:

document.getElementById(id+'_tbl').style.width='100%'


Para hacer la altura del fluido:

Cambie dinámicamente document.getElementById(id+'_ifr').style.height a la altura que desee, a través de JS.
Este es el script que estoy usando para esto:

function toScreenHeight(id, minus) {
    var height;

    if (typeof(window.innerHeight) == "number") //non-IE
        height = window.innerHeight;
    else if (document.documentElement && document.documentElement.clientHeight) //IE 6+ strict mode
        height = document.documentElement.clientHeight;
    else if (document.body && document.body.clientHeight) //IE 4 compatible / IE quirks mode
        height = document.body.clientHeight;

    document.getElementById(id).style.height = (height - minus) + "px";
}

Puede usar las llamadas de código y función dentro de onload y onresize body evento.

 14
Author: igorsantos07,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-10-01 21:01:42

En tinymce 3.4.6, set

width:'100%'

En la opción init resolverá el problema.

 9
Author: ZHAO Xudong,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-10-26 04:52:15

Si está haciendo tiny MCE dinámicamente a través de JS, puede encontrarse con problemas de tiempo en los que el editor de MCE aún no está disponible para los ajustes de estilo. Para combatir esto, puedes usar un tiempo de espera de la vieja escuela.

En este ejemplo, estoy usando un espacio de nombres "j" para jQuery. Si su editor está en un div fluido que cambia de tamaño, puede incluir esto en una window(ventana).redimensionar (function () {}); oyente.

setTimeout(function(){ 
  $j('.mceEditor').css('width','100%').css('minHeight','240px');
  $j('.mceLayout').css('width','100%').css('minHeight','240px');
  $j('.mceIframeContainer').css('width','100%').css('minHeight','240px');
  $j('#'+[INSERT TEXTAREA ID HERE]+'_ifr').css('width','100%').css('minHeight','240px');
},500) 
 3
Author: Noel Baron,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-09-29 16:17:21

Ninguno de los anteriores funcionaban para mí en TinyMCE v4, por lo que mi solución fue calcular la altura en función de las barras de herramientas/barra de menú/barra de estado, y luego establecer la altura del editor, teniendo en cuenta esas alturas.

function resizeEditor(myHeight) {
    window.console.log('resizeEditor');
    myEditor = getEditor();
    if (myEditor) {
        try {
            if (!myHeight) {            
                var targetHeight = window.innerHeight; // Change this to the height of your wrapper element
                var mce_bars_height = 0;
                $('.mce-toolbar, .mce-statusbar, .mce-menubar').each(function(){
                    mce_bars_height += $(this).height();
                });
                window.console.log('mce bars height total: '+mce_bars_height);                          
                myHeight = targetHeight - mce_bars_height - 8;  // the extra 8 is for margin added between the toolbars
            }
            window.console.log('resizeEditor: ', myHeight);
            myEditor.theme.resizeTo('100%', myHeight);  // sets the dimensions of the editable area
        }
        catch (err) {
        }
    }
}

En mi caso, quería que la ventana del editor coincidiera con el ancho y el alto del window real, ya que el editor aparecería en una ventana emergente. Para detectar cambios y redimensionar, establezco esto en una devolución de llamada:

window.onresize = function() {
    resizeEditor();
}
 3
Author: Kyle Falconer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-08-08 15:20:23

Con la versión 4 y la opción de usar flexbox layout en el navegador hice lo siguiente para obtener una experiencia de edición de ancho y alto completa del div padre.

Debería ser fácil poner el css en un archivo si prefiere agregarlo a sus estilos existentes.

var css = '.tinycme-full .mce-edit-area {display:flex;flex-flow:column;} .tinycme-full .mce-edit-area iframe {flex:1 1 auto;}  .tinycme-full {height:100%;} .tinycme-full .mce-tinymce.mce-container { width:100%;height:100%;border:0; } .tinycme-full .mce-panel{border:0} .tinycme-full .mce-container-body.mce-stack-layout {display: flex; flex-flow: column;height: 100%;} .tinycme-full .mce-stack-layout-item{  flex: 0 0 auto;} .tinycme-full .mce-edit-area{flex:1 1 auto;} ',
    head = document.head || document.getElementsByTagName('head')[0],
    style = document.createElement('style');

style.type = 'text/css';
if (style.styleSheet) {
    style.styleSheet["cssText"] = css;
} else {
    style.appendChild(document.createTextNode(css));
}

head.appendChild(style);

La idea es que haga que todos los divs necesarios ocupen tanto espacio de columna como sea necesario para llenar el padre 100% y se hace poniendo un div alrededor de su área de texto: <div class="tinycme-full"> <textarea ... /></div>

No hay jquery u otras dependencias necesario y ahora llena el padre 100%. introduzca la descripción de la imagen aquí

 2
Author: Poul K. Sørensen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-06-24 22:28:29

Tuve el mismo problema, después de leer este hilo terminé con este código

init_instance_callback: function (inst) { 
  setTimeout(function () {
    document.getElementById(inst.id + '_ifr').style.height= (document.getElementById("theContainerDiv").offsetHeight-85) + 'px';
   },1000);
},

Redimensioné el elemento "_ifm" en lugar del "_tbl", ya que redimensionar el "_tbl" no redimensionó el área de edición para mí. Luego dejo un poco de espacio para la barra de herramientas y la barra de estado haciendo que el "_ifr" sea 85 píxeles más corto que el div del contenedor.

Tuve que usar setTimeout para que funcionara, tal vez porque tengo una animación que muestra el elemento contenedor.

 1
Author: emmanuel2004,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-03-05 12:23:40

SyCoDeR tiene razón, pero seguí un camino ligeramente diferente, aunque probablemente con los mismos resultados.

/*Container, container body, iframe*/
.mce-tinymce, .mce-container-body, #code_ifr {
    min-height: 100% !important;
}
/*Container body*/
.mce-container-body {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
}
/*Editing area*/
.mce-container-body .mce-edit-area {
    position: absolute;
    top: 69px;
    bottom: 37px;
    left: 0;
    right: 0;
}
/*Footer*/
.mce-tinymce .mce-statusbar {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
}

Revisado porque TinyMCE cambia los id con adiciones o eliminaciones de menú/barra de herramientas. Esto funciona sin importar lo que hagas con él.

 1
Author: liquibyte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-27 02:48:44

La envoltura de iframe (su ID termina por _ifr) es el primer padre de span que tiene aplicación como rol . Por lo tanto, para obtener la envoltura :

$('span[role=application]').parents(':eq(0)')

Así que para cambiar el tamaño de la altura:

$('[id$=_ifr]').css('height',$('span[role=application]').parents(':eq(0)').css('height'))

Para redimensionar el ancho

$('[id$=_ifr]').css('width',$('span[role=application]').parents(':eq(0)').css('width'))
 0
Author: Abdennour TOUMI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-04-29 01:25:12

Estoy usando la solución css pura para lograr esto (TinyMCE 4.0.20).

  1. Establezca la altura del iframe en 100%:

    tinymce.init({ altura: '100%' })

  2. Añadir estilos al contenedor iframe de redimensionamiento automático:

    .mce-tinymce { altura: auto; anchura: 100%; posición: absoluta; izquierda: 0; arriba: 0; abajo: 0; }

    .bq-editor .mce-contenedor-cuerpo { altura: 100%; }

    .bq-editor .mce-edit-área { position: absolute; top: 57px; parte inferior: 0; ancho: 100%; altura: auto; }

Nota: Tengo una línea de la barra de herramientas, y arriba: 57px; en.bq-editor .mce-edit-área es el relleno de la barra de herramientas.

 0
Author: SyCoDeR,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-30 10:59:50

Ninguna de estas soluciones funcionó al 100% para mí. Necesitaba la altura para ajustar en la inicialización y durante las ediciones. Lo que hice fue tomar la altura del elemento HTML en el iFrame, y luego aplicar la altura al iFrame con un extra de 100px.

Aquí está mi solución: (agregado img max-width para imágenes responsivas)

En la inicialización

   setup: function(editor) { 
        editor.on('init', function (e) { 
            $("#editor_textarea_ifr").contents().find('img').css("max-width","100%");
            iframeHeight = $("#editor_textarea_ifr").contents().find("html").height();            
            $("#editor_textarea_ifr").css("height",iframeHeight + 100);                     
        });             
    },

En el cambio de nodo (ediciones)

  init_instance_callback: function (editor) {
    editor.on('NodeChange', function (e) {
      $("#editor_textarea_ifr").contents().find('img').css("max-width","100%");               
      iframeHeight = $("#editor_textarea_ifr").contents().find("html").height();              
      $("#editor_textarea_ifr").css("height",iframeHeight + 100);   
    });
}   
 0
Author: DobotJr,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-16 16:21:06