Foros del Web » Programando para Internet » Javascript »

Problema If de boton 1 vez pulsado tenga 1 color y al volverlo a pulsar el 1er color

Estas en el tema de Problema If de boton 1 vez pulsado tenga 1 color y al volverlo a pulsar el 1er color en el foro de Javascript en Foros del Web. Código: function Funcion2(COLOR) { var aux ; if (document.getElementById(COLOR).style.background == "#ffffff"){ document.getElementById(COLOR).style.background="#000000"; } else { document.getElementById(COLOR).style.background = "#ffffff"; } } Lo que quiero esque el ...
  #1 (permalink)  
Antiguo 11/11/2010, 05:38
 
Fecha de Ingreso: mayo-2009
Mensajes: 15
Antigüedad: 15 años
Puntos: 0
Problema If de boton 1 vez pulsado tenga 1 color y al volverlo a pulsar el 1er color

Código:
	function Funcion2(COLOR) {
	var aux ;
	
		if (document.getElementById(COLOR).style.background == "#ffffff"){
				document.getElementById(COLOR).style.background="#000000";		
		}
		else {
				document.getElementById(COLOR).style.background = "#ffffff";
		}	
	}
Lo que quiero esque el boton si tiene el fondo blanco lo pase a negro y si esta en negro lo pase a blanco, pero siempre se desvia por el Else y lo pone de color blanco.

Saludos!
  #2 (permalink)  
Antiguo 11/11/2010, 06:18
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Sabadell
Mensajes: 4.897
Antigüedad: 16 años, 1 mes
Puntos: 574
Respuesta: Problema If de boton 1 vez pulsado tenga 1 color y al volverlo a pulsar el

1. El nombre del atributo es backgroundColor no background.
2. Si haces un

Código Javascript:
Ver original
  1. alert(document.getElementById(COLOR.id).style.backgroundColor)

veras que en vez de decir #000000 dice rgb(0, 0, 0).

Y ahora alucina con la solución que te he encontrado

Código Javascript:
Ver original
  1. function Funcion2(COLOR) {
  2.     var aux=document.getElementById(COLOR.id).style.backgroundColor;
  3.     alert(aux);
  4.         if (rgbConvert(aux) == "#000000"){
  5.                 document.getElementById(COLOR.id).style.backgroundColor="#ffffff";     
  6.         }
  7.         else {
  8.                 document.getElementById(COLOR.id).style.backgroundColor = "#000000";
  9.         }  
  10.     }
  11. function rgbConvert(str) {
  12.    str = str.replace(/rgb\(|\)/g, "").split(",");
  13.    str[0] = parseInt(str[0], 10).toString(16).toLowerCase();
  14.    str[1] = parseInt(str[1], 10).toString(16).toLowerCase();
  15.    str[2] = parseInt(str[2], 10).toString(16).toLowerCase();
  16.    str[0] = (str[0].length == 1) ? '0' + str[0] : str[0];
  17.    str[1] = (str[1].length == 1) ? '0' + str[1] : str[1];
  18.    str[2] = (str[2].length == 1) ? '0' + str[2] : str[2];
  19.    return ('#' + str.join(""));
  20. }


Código HTML:
Ver original
  1. <input name="boton" type="button" id="boton" onClick="Funcion2(this)" style="background-color: #000000">

Una funcion que convierte el texto rgb(0,0,0) a #000000

Fijate que uso this para pasar el objeto, esto lo puedes cambiar y poner directamente el id del boton.

Tambien puedes sacar el alert().

Lo he encontrado aqui.

Si alguien lo sabe, nos podría explicar el porque de esa, aparentemente, incoherencia de javascript.


Claro que como se trata de textos tambien se puede hacer esto y funciona

Código Javascript:
Ver original
  1. function Funcion2(COLOR) {
  2.     var aux=document.getElementById(COLOR.id).style.backgroundColor;
  3.     alert(aux);
  4.         if (aux == "rgb(0, 0, 0)"){
  5.                 document.getElementById(COLOR.id).style.backgroundColor="#ffffff";     
  6.         }
  7.         else {
  8.                 document.getElementById(COLOR.id).style.backgroundColor = "#000000";
  9.         }  
  10.     }

Fijate en las comillas aux == "rgb(0, 0, 0)"

Quim
  #3 (permalink)  
Antiguo 11/11/2010, 10:35
 
Fecha de Ingreso: mayo-2009
Mensajes: 15
Antigüedad: 15 años
Puntos: 0
Respuesta: Problema If de boton 1 vez pulsado tenga 1 color y al volverlo a pulsar el

osti no me habia fijado que lo comparaba en rgb, yo pensaba que si pasaba algo asi lo convertia solo.

muchas gracias, mañana lo testeo en cuanto llegue al curro!
  #4 (permalink)  
Antiguo 11/11/2010, 14:12
Avatar de Tecna  
Fecha de Ingreso: enero-2010
Mensajes: 291
Antigüedad: 14 años, 3 meses
Puntos: 45
Respuesta: Problema If de boton 1 vez pulsado tenga 1 color y al volverlo a pulsar el

Buenas,

la propiedad style sólo devolverá un valor si se ha definido previamente mediante el atributo style del elemento html o mediante las propiedades de estilo del objeto CSS2Properties. Si se definió con la etiqueta <style> o en una hoja de estilos externa el valor devuelto sería una cadena vacia.

En cuanto a lo de como se codifica el valor no tiene nada que ver con javascript, ya que todas las formas válidas para css lo serían también para javascript, pero como se muestra o almacena el valor depende exclusivamente del navegador, firefox y chrome lo muestran en rgb pero opera, konqueror y explorer lo muestran en hexadecimal.
  #5 (permalink)  
Antiguo 12/11/2010, 02:20
Colaborador
 
Fecha de Ingreso: marzo-2008
Ubicación: Sabadell
Mensajes: 4.897
Antigüedad: 16 años, 1 mes
Puntos: 574
Respuesta: Problema If de boton 1 vez pulsado tenga 1 color y al volverlo a pulsar el

Pues Tecna tiene razon y por tanto la solucion no sierve para todos los navegadores.

Una vez mas tendremos que programar dos versiones de lo mismo, en este caso es fàcil

Código HTML:
Ver original
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <title>Documento sin t&iacute;tulo</title>
  3. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  4. </head>
  5. <script language="JavaScript" type="text/JavaScript">
  6. function Funcion2(COLOR) {
  7.     var aux=document.getElementById(COLOR.id).style.backgroundColor;//innecesario
  8.     alert(aux);//innecesario
  9.     if(document.getElementById(COLOR.id).style.backgroundColor.indexOf("#")!=-1){
  10.             aux=document.getElementById(COLOR.id).style.backgroundColor;
  11.         }else{
  12.             aux=rgbConvert(document.getElementById(COLOR.id).style.backgroundColor);
  13.         }
  14.         if (aux == "#000000"){
  15.                 document.getElementById(COLOR.id).style.backgroundColor="#ffffff";      
  16.         }
  17.         else {
  18.                 document.getElementById(COLOR.id).style.backgroundColor = "#000000";
  19.         }  
  20.     }
  21. function rgbConvert(str) {
  22.    str = str.replace(/rgb\(|\)/g, "").split(",");
  23.    str[0] = parseInt(str[0], 10).toString(16).toLowerCase();
  24.    str[1] = parseInt(str[1], 10).toString(16).toLowerCase();
  25.    str[2] = parseInt(str[2], 10).toString(16).toLowerCase();
  26.    str[0] = (str[0].length == 1) ? '0' + str[0] : str[0];
  27.    str[1] = (str[1].length == 1) ? '0' + str[1] : str[1];
  28.    str[2] = (str[2].length == 1) ? '0' + str[2] : str[2];
  29.    return ('#' + str.join(""));
  30. }</script>
  31.  
  32. <input name="boton" type="button" id="boton" onClick="Funcion2(this)" style="background-color: #000000">
  33. </body>
  34. </html>

Quizas una forma mas elegante seria definir dos clases CSS (digamos botonblanco, botonnegro) usar .className en la función


Código HTML:
Ver original
  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
  2. <title>Documento sin t&iacute;tulo</title>
  3. <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
  4. </head>
  5. <script language="JavaScript" type="text/JavaScript">
  6. function Funcion2(COLOR) {
  7.     var aux=document.getElementById(COLOR.id).className;//innecesario
  8.     alert(aux);//innecesario
  9.         if (document.getElementById(COLOR.id).className == "botonBlanco"){
  10.                 document.getElementById(COLOR.id).className = "botonNegro";      
  11.         }
  12.         else {
  13.                 document.getElementById(COLOR.id).className = "botonBlanco";
  14.         }  
  15.     }
  16. .botonBlanco{
  17.         background-color: #FFFFFF;
  18. }
  19.  
  20. .botonNegro{
  21.          background-color: #000000;
  22. }
  23.  
  24. <input name="boton" type="button" id="boton" onClick="Funcion2(this)" class="botonBlanco">
  25. </body>
  26. </html>


Elige la que mas te guste, estas funcionan en FF y IE.

Quim
  #6 (permalink)  
Antiguo 16/11/2010, 05:25
 
Fecha de Ingreso: mayo-2009
Mensajes: 15
Antigüedad: 15 años
Puntos: 0
Busqueda Respuesta: Problema If de boton 1 vez pulsado tenga 1 color y al volverlo a pulsar el

Este codigo me ha funcionado alfinal, el problema esque en firefox funciona pero en internet iexplorer no, y todos los que visitan la web entran desde IEXPLORER

Código:
      function Funcion2(COLOR) {
		var aux=document.getElementById(COLOR).style.backgroundColor;
		if (aux == "rgb(152, 251, 152)"){
                      document.getElementById(COLOR).style.backgroundColor="#ffffff";
					  document.getElementById(COLOR).style.background="#ffffff"; 					  
              }
              else {
                      document.getElementById(COLOR).style.backgroundColor="#98FB98";
					  document.getElementById(COLOR).style.background="#98FB98";
              }  
          }
voy a probar cambiando de clases
  #7 (permalink)  
Antiguo 17/11/2010, 05:26
 
Fecha de Ingreso: mayo-2009
Mensajes: 15
Antigüedad: 15 años
Puntos: 0
Respuesta: Problema If de boton 1 vez pulsado tenga 1 color y al volverlo a pulsar el

hay alguna forma de cambiar el fondo de un boton en Iexplorer?
  #8 (permalink)  
Antiguo 01/04/2011, 08:42
 
Fecha de Ingreso: marzo-2011
Mensajes: 12
Antigüedad: 13 años, 1 mes
Puntos: 0
Respuesta: Problema If de boton 1 vez pulsado tenga 1 color y al volverlo a pulsar el

Cita:
Iniciado por quimfv Ver Mensaje
1. El nombre del atributo es backgroundColor no background.
2. Si haces un

Código Javascript:
Ver original
  1. alert(document.getElementById(COLOR.id).style.backgroundColor)

veras que en vez de decir #000000 dice rgb(0, 0, 0).

Y ahora alucina con la solución que te he encontrado

Código Javascript:
Ver original
  1. function Funcion2(COLOR) {
  2.     var aux=document.getElementById(COLOR.id).style.backgroundColor;
  3.     alert(aux);
  4.         if (rgbConvert(aux) == "#000000"){
  5.                 document.getElementById(COLOR.id).style.backgroundColor="#ffffff";     
  6.         }
  7.         else {
  8.                 document.getElementById(COLOR.id).style.backgroundColor = "#000000";
  9.         }  
  10.     }
  11. function rgbConvert(str) {
  12.    str = str.replace(/rgb\(|\)/g, "").split(",");
  13.    str[0] = parseInt(str[0], 10).toString(16).toLowerCase();
  14.    str[1] = parseInt(str[1], 10).toString(16).toLowerCase();
  15.    str[2] = parseInt(str[2], 10).toString(16).toLowerCase();
  16.    str[0] = (str[0].length == 1) ? '0' + str[0] : str[0];
  17.    str[1] = (str[1].length == 1) ? '0' + str[1] : str[1];
  18.    str[2] = (str[2].length == 1) ? '0' + str[2] : str[2];
  19.    return ('#' + str.join(""));
  20. }


Código HTML:
Ver original
  1. <input name="boton" type="button" id="boton" onClick="Funcion2(this)" style="background-color: #000000">

Una funcion que convierte el texto rgb(0,0,0) a #000000

Fijate que uso this para pasar el objeto, esto lo puedes cambiar y poner directamente el id del boton.

Tambien puedes sacar el alert().

Lo he encontrado [URL="http://www.tek-tips.com/viewthread.cfm?qid=1436140&page=11"]aqui[/URL].

Si alguien lo sabe, nos podría explicar el porque de esa, aparentemente, incoherencia de javascript.


Claro que como se trata de textos tambien se puede hacer esto y funciona

Código Javascript:
Ver original
  1. function Funcion2(COLOR) {
  2.     var aux=document.getElementById(COLOR.id).style.backgroundColor;
  3.     alert(aux);
  4.         if (aux == "rgb(0, 0, 0)"){
  5.                 document.getElementById(COLOR.id).style.backgroundColor="#ffffff";     
  6.         }
  7.         else {
  8.                 document.getElementById(COLOR.id).style.backgroundColor = "#000000";
  9.         }  
  10.     }

Fijate en las comillas aux == "rgb(0, 0, 0)"

Quim



Hola, gracias por tu ayuda, me ha servido el código... el problema que tengo es que el boton al ser presionado no permance con el color cambiado, sino que vuelve a su estado original en menos de un segundo =( ... cuando se presiona un boton el ejecuta una acción(muestra una tabla)... quiero que quede en negro cuando se presione, hasta que se vuelva a presionar otro boton (son 7 botones, cada uno genera una tabla diferente) . Para generar las tablas tengo programado en php. por favor, me podrias ayudar? gracias

Etiquetas: color, pulsado, pulsar, botones
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 11:13.