Foros del Web » Programando para Internet » Javascript »

Cambiar texto poco a poco

Estas en el tema de Cambiar texto poco a poco en el foro de Javascript en Foros del Web. Hola quiero hacer que cando se pulsa un boton el texto aparesca poco a poco de modo que en algunos segundos se ha mostrado pero ...
  #1 (permalink)  
Antiguo 22/08/2012, 15:56
Avatar de patilanz  
Fecha de Ingreso: enero-2012
Mensajes: 880
Antigüedad: 12 años, 3 meses
Puntos: 29
Pregunta Cambiar texto poco a poco

Hola quiero hacer que cando se pulsa un boton el texto aparesca poco a poco de modo que en algunos segundos se ha mostrado pero que sea de esta manera:
1: T
2: Te
3:Tex
4:Text
5:Texto
He intentado hacer lo con este codigo :

Código Javascript:
Ver original
  1. function mostrar_restaurantea() {
  2.     var b = Array('Б','ъ','л','г','а','р','с','к','и',' ','р','е','с','т','о','р','а','н','т',' ','п','р','е','д','л','а','г','а',' ','а','в','т','е','н','т','и','ч','н','a','Б','ъ','л','г','а','р','с','к','а',' ','к','у','х','н','я',' ','в',' ','у','ю','т','н','а',' ','о','б','с','т','а','н','о','в','к','а',' ','в',' ','г','р','а','д',' ','К','а','р','л','о','в','о','.');
  3.     var asd1;
  4.     asd1 += 1;
  5.     var o = '';
  6.     o += b[asd1];
  7.     document.getElementById('contenido').innerHTML = o;
  8.     if(asd1 > 89) {
  9.         clearInterval('interval');
  10.     }
  11.    
  12. }
  13. function mostrar_restaurante() {
  14.     var titulo = 'Ресторант фиеста';
  15.     var b = Array('Б','ъ','л','г','а','р','с','к','и',' ','р','е','с','т','о','р','а','н','т',' ','п','р','е','д','л','а','г','а',' ','а','в','т','е','н','т','и','ч','н','a','Б','ъ','л','г','а','р','с','к','а',' ','к','у','х','н','я',' ','в',' ','у','ю','т','н','а',' ','о','б','с','т','а','н','о','в','к','а',' ','в',' ','г','р','а','д',' ','К','а','р','л','о','в','о','.');
  16.     var indice;
  17.     var ind = 50;
  18.     var h;
  19.  
  20.    
  21.    
  22.    
  23.  
  24.    
  25.         for(indice = 1; indice < b.length; indice ++) {
  26.         interval = setTimeout('mostrar_restaurantea()',ind);
  27.         ind += 50;
  28.         }

Pero no me funciona...
Alguna manera de hacer lo ?
Este efecto tiene su propio nombre?

Gracias :)
  #2 (permalink)  
Antiguo 22/08/2012, 16:10
Avatar de garciasanchezdani  
Fecha de Ingreso: noviembre-2011
Mensajes: 429
Antigüedad: 12 años, 5 meses
Puntos: 51
Respuesta: Cambiar texto poco a poco

Hola patilanz
Aquí está lo que buscas: http://jsfiddle.net/VZvK7/
Saludos, Daniel
__________________
Diseño Web Jaén
  #3 (permalink)  
Antiguo 22/08/2012, 16:17
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 20 años
Puntos: 834
Respuesta: Cambiar texto poco a poco

¿Le estás recomendando que cargue jQuery para eso?

Te recomiendo que busques en el foro por efecto máquina de escribir o algo semejante -el tema se trató varias veces-.


PD: Estoy de acuerdo en usar jQuery para cosas complejas, pero no para algo tan simple. Y estoy de acuerdo en web: en mobile, desperdiciar 4 Joules de batería cada vez que carga una página con jQuery seguro que hay que pensarlo muy bien antes de hacerlo
  #4 (permalink)  
Antiguo 22/08/2012, 16:22
Avatar de garciasanchezdani  
Fecha de Ingreso: noviembre-2011
Mensajes: 429
Antigüedad: 12 años, 5 meses
Puntos: 51
Respuesta: Cambiar texto poco a poco

Cita:
Iniciado por Panino5001 Ver Mensaje
¿Le estás recomendando que cargue jQuery para eso?

Te recomiendo que busques en el foro por efecto máquina de escribir o algo semejante -el tema se trató varias veces-.


PD: Estoy de acuerdo en usar jQuery para cosas complejas, pero no para algo tan simple. Y estoy de acuerdo en web: en mobile, desperdiciar 4 Joules de batería cada vez que carga una página con jQuery seguro que hay que pensarlo muy bien antes de hacerlo
Hola Panino5001, te entiendo...pero yo simplemente he aportado un enlace que contiene una solución a lo que está buscando, nada más.
Saludos
__________________
Diseño Web Jaén
  #5 (permalink)  
Antiguo 22/08/2012, 16:30
Avatar de Dradi7  
Fecha de Ingreso: junio-2008
Ubicación: Peru - Lima
Mensajes: 1.518
Antigüedad: 15 años, 10 meses
Puntos: 220
Respuesta: Cambiar texto poco a poco

Sencillamete puedes hacer eso

Código HTML:
Ver original
  1. <div id="mesage" />

Código Javascript:
Ver original
  1. var mesage = "Hola Mundo";
  2. var i = 0;
  3. var OK = setInterval(function(){
  4.     if(i<mesage.length){
  5.         document.getElementById('mesage').innerHTML=mesage.substr(0,i+1);
  6.     }else{
  7.         clearInterval(OK);
  8.         alert('FIN');
  9.     }
  10.     i++;
  11. },100);
__________________
La clave de todo triunfador es eliminar todas sus excusas y sus limitaciones
  #6 (permalink)  
Antiguo 22/08/2012, 17:33
Avatar de Panino5001
Me alejo de Omelas
 
Fecha de Ingreso: mayo-2004
Ubicación: -34.637167,-58.462984
Mensajes: 5.148
Antigüedad: 20 años
Puntos: 834
Respuesta: Cambiar texto poco a poco

garciasanchezdani, pensé que era tu código; mejor no contribuir a la confusión general

Dradi7, gracias a explorer no es buena idea ponerle el mismo nombre que el valor de un atributo id a una variable global (aunque en este caso no afecte).

Código PHP:
<!DOCTYPE html>
<
html>
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<
title></title>
</
head>

<
body>
<
div id="m"></div>
<
script type="text/javascript">
//esto, tomado de https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach, sólo es necesario para navegadores obsoletos:
if ( !Array.prototype.forEach ) {
 
  Array.
prototype.forEach = function( callbackthisArg ) {
 
    var 
Tk;
 
    if ( 
this == null ) {
      throw new 
TypeError"this is null or not defined" );
    }
 
    
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
    
var Object(this);
 
    
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    
var len O.length >>> 0// Hack to convert O.length to a UInt32
 
    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    
if ( {}.toString.call(callback) != "[object Function]" ) {
      throw new 
TypeErrorcallback " is not a function" );
    }
 
    
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    
if ( thisArg ) {
      
thisArg;
    }
 
    
// 6. Let k be 0
    
0;
 
    
// 7. Repeat, while k < len
    
while( len ) {
 
      var 
kValue;
 
      
// a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      
if ( k in O ) {
 
        
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
        
kValue O];
 
        
// ii. Call the Call internal method of callback with T as the this value and
        // argument list containing kValue, k, and O.
        
callback.callTkValuek);
      }
      
// d. Increase k by 1.
      
k++;
    }
    
// 8. return undefined
  
};
}

//con esto bastaría para cualquier navegador moderno:
var txt = ("Hola Mundo").split('').forEach(function(t,i){setTimeout(function(){document.getElementById('m').innerHTML+=t;},100*i);});
</script>
</body>
</html> 

Última edición por Panino5001; 22/08/2012 a las 17:50
  #7 (permalink)  
Antiguo 22/08/2012, 23:43
Avatar de patilanz  
Fecha de Ingreso: enero-2012
Mensajes: 880
Antigüedad: 12 años, 3 meses
Puntos: 29
Respuesta: Cambiar texto poco a poco

Hola,
Gracias Dradi7 y Panino5001. Probe los dos codigos y los dos funcionan pero si quiero poner le alguna etiqueta como por ejemplo un <h3> no se como hacer lo.

Gracias :)
  #8 (permalink)  
Antiguo 23/08/2012, 00:31
Avatar de patilanz  
Fecha de Ingreso: enero-2012
Mensajes: 880
Antigüedad: 12 años, 3 meses
Puntos: 29
Pregunta Respuesta: Cambiar texto poco a poco

Cita:
Iniciado por Dradi7 Ver Mensaje
Sencillamete puedes hacer eso

Código HTML:
Ver original
  1. <div id="mesage" />

Código Javascript:
Ver original
  1. var mesage = "Hola Mundo";
  2. var i = 0;
  3. var OK = setInterval(function(){
  4.     if(i<mesage.length){
  5.         document.getElementById('mesage').innerHTML=mesage.substr(0,i+1);
  6.     }else{
  7.         clearInterval(OK);
  8.         alert('FIN');
  9.     }
  10.     i++;
  11. },100);
Hola , gracias por tu respuesta pero hay alguna manera de cancelar el intervalo OK desde otra funciona ??

Gracias :)
  #9 (permalink)  
Antiguo 23/08/2012, 07:56
Avatar de Dradi7  
Fecha de Ingreso: junio-2008
Ubicación: Peru - Lima
Mensajes: 1.518
Antigüedad: 15 años, 10 meses
Puntos: 220
Respuesta: Cambiar texto poco a poco

Cita:
Iniciado por Panino5001 Ver Mensaje
garciasanchezdani, pensé que era tu código; mejor no contribuir a la confusión general

Dradi7, gracias a explorer no es buena idea ponerle el mismo nombre que el valor de un atributo id a una variable global (aunque en este caso no afecte).

Código PHP:
<!DOCTYPE html>
<
html>
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<
title></title>
</
head>

<
body>
<
div id="m"></div>
<
script type="text/javascript">
//esto, tomado de https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/forEach, sólo es necesario para navegadores obsoletos:
if ( !Array.prototype.forEach ) {
 
  Array.
prototype.forEach = function( callbackthisArg ) {
 
    var 
Tk;
 
    if ( 
this == null ) {
      throw new 
TypeError"this is null or not defined" );
    }
 
    
// 1. Let O be the result of calling ToObject passing the |this| value as the argument.
    
var Object(this);
 
    
// 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
    // 3. Let len be ToUint32(lenValue).
    
var len O.length >>> 0// Hack to convert O.length to a UInt32
 
    // 4. If IsCallable(callback) is false, throw a TypeError exception.
    // See: http://es5.github.com/#x9.11
    
if ( {}.toString.call(callback) != "[object Function]" ) {
      throw new 
TypeErrorcallback " is not a function" );
    }
 
    
// 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
    
if ( thisArg ) {
      
thisArg;
    }
 
    
// 6. Let k be 0
    
0;
 
    
// 7. Repeat, while k < len
    
while( len ) {
 
      var 
kValue;
 
      
// a. Let Pk be ToString(k).
      //   This is implicit for LHS operands of the in operator
      // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
      //   This step can be combined with c
      // c. If kPresent is true, then
      
if ( k in O ) {
 
        
// i. Let kValue be the result of calling the Get internal method of O with argument Pk.
        
kValue O];
 
        
// ii. Call the Call internal method of callback with T as the this value and
        // argument list containing kValue, k, and O.
        
callback.callTkValuek);
      }
      
// d. Increase k by 1.
      
k++;
    }
    
// 8. return undefined
  
};
}

//con esto bastaría para cualquier navegador moderno:
var txt = ("Hola Mundo").split('').forEach(function(t,i){setTimeout(function(){document.getElementById('m').innerHTML+=t;},100*i);});
</script>
</body>
</html> 
Si tienes razón pero solo era un ejemplo explicativo nada mas de como lo debia hacer, se me paso al no considerar esto
__________________
La clave de todo triunfador es eliminar todas sus excusas y sus limitaciones
  #10 (permalink)  
Antiguo 23/08/2012, 07:57
Avatar de Dradi7  
Fecha de Ingreso: junio-2008
Ubicación: Peru - Lima
Mensajes: 1.518
Antigüedad: 15 años, 10 meses
Puntos: 220
Respuesta: Cambiar texto poco a poco

Cita:
Iniciado por patilanz Ver Mensaje
Hola , gracias por tu respuesta pero hay alguna manera de cancelar el intervalo OK desde otra funciona ??

Gracias :)
Solamente tienes que poner el clearInterval dentro de otra funcion y listo
__________________
La clave de todo triunfador es eliminar todas sus excusas y sus limitaciones
  #11 (permalink)  
Antiguo 23/08/2012, 10:53
Avatar de patilanz  
Fecha de Ingreso: enero-2012
Mensajes: 880
Antigüedad: 12 años, 3 meses
Puntos: 29
Respuesta: Cambiar texto poco a poco

Cita:
Iniciado por Dradi7 Ver Mensaje
Solamente tienes que poner el clearInterval dentro de otra funcion y listo
Ya lo hize pero no me funciona ...
Lo que intente hacer que que son varios apartados y quiero hacer que al pulsar en este que se muestran las palabras poco a poco y cuando todabia no se an mostrado todas si se pulsa a otro apartado o otro botón se muestra otra cosa. Pero lo que me sucede es que cuando esta activo el intervalo de las letras y luego al pulsar a otro boton solo muestra por 1 segundo el contenido y vuelve a continuar con las letras o con el intervalo . Intente con clearInterval pero queda igual como que no esta escrito...

De modo que en otra variable he puesto:

clearInterval(mostrar);

Y me muestra error de no definido...
Luego probe poner en la funcion que crea el intervalo poner:

return mostrar;

Y luego en la otra funciona puse :

var mostrar = mostrar_restaurante();
clearInterval(mostrar);

Pero tampoco funciono... como solucionar lo ?

Gracias :)

Última edición por patilanz; 24/08/2012 a las 00:43
  #12 (permalink)  
Antiguo 25/08/2012, 01:22
Avatar de patilanz  
Fecha de Ingreso: enero-2012
Mensajes: 880
Antigüedad: 12 años, 3 meses
Puntos: 29
Respuesta: Cambiar texto poco a poco

Hola, Dradi7 en tu codigo encontre un error.
Cuando se pulsa una vez el boton para mostrar el texto y luego se pulsa de nuevo en el el intervalo empieza a declararse las veces que se pulsa y el texto se escribe parpadeando y se borra y aparece de nuevo (errores) o si se pulsa sobre otro boton que cambia el mismo texto lo que pasa es que el texto del otro boton aparece por 1 segundo y luego desaparece y se continua con el intervalo del anterior ...
Asi no se puede cancelar el intervalo...

Probe diferentes formas de resolver lo pero no lo conseguí.
Como resolver lo?

Gracias :)

Etiquetas: efecto, texto_poco_poco
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 16:31.