JavaScript - deshacer cambio de backgroundColor onclick

 
Vista:

deshacer cambio de backgroundColor onclick

Publicado por Oriol (5 intervenciones) el 02/03/2016 13:19:36
Saludos a tod@s,

novato y mi primera pregunta, o sea que gracias de antemano.

Necesito cambiar el color de fondo de parte de unos textos al clicar un botón. Lo he conseguido con este script:

1
2
3
4
5
6
7
8
<script type="text/javascript">
function hl_etim() {
    var x = document.getElementsByClassName("etim");
    var i;
    for (i = 0; i < x.length; i++) {
      x[i].style.backgroundColor = "turquoise";
}
</script>

Como hago ahora para que al volver a clicar vuelva al color original? Lo he intentado con if...else,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<script type="text/javascript">
function hl_etim() {
 if(etim.style.backgroundColor == "transparent") {
    var x = document.getElementsByClassName("etim");
    var i;
    for (i = 0; i < x.length; i++) {
      x[i].style.backgroundColor = "turquoise";
  }
  else {
    var a = document.getElementsByClassName("etim");
    var b;
    for (b = 0; b < a.length; b++) {
      a[b].style.backgroundColor = "transparent";
  }
}
</script>

pero no funciona. Alguna idea?

Gracias!
Valora esta pregunta
Me gusta: Está pregunta es útil y esta claraNo me gusta: Está pregunta no esta clara o no es útil
0
Responder
Imágen de perfil de xve
Val: 3.162
Oro
Ha mantenido su posición en JavaScript (en relación al último mes)
Gráfica de JavaScript

deshacer cambio de backgroundColor onclick

Publicado por xve (2100 intervenciones) el 02/03/2016 20:07:35
Hola Oriol, no nos has mostrado el código HTML, por lo que no he podido probarlo, pero creo que esta linea esta mal...

En vez de:
1
if(etim.style.backgroundColor == "transparent") {

debería ser algo como:
1
if(document.getElementsByClassName("etim")[0].style.backgroundColor == "transparent") {

Puedes probar y comentar?
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar

deshacer cambio de backgroundColor onclick

Publicado por Oriol (5 intervenciones) el 03/03/2016 20:46:01
Tampoco lo sé hacer funcionar.

Con un solo fragmento a destacar, utilizando 'span id' y 'getElementbyId' funciona (abajo el html), pero al tener más de un texto a resaltar hay que utilizar 'getElementsbyClassName', que no funciona con 'id' y funciona con 'class'.
Al utilizar 'getElementsbyClassName' y 'class' me funciona la primera vez, pero al poner el condicional no funciona. Creo que es algo del if...else, pero no veo que puede ser.

Gracias por la respuesta. Pongo un html con lo que me funciona. Ahora me falta unir el condicional con la función

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>prova_js</title>
    <style>span.etim {background:transparent};</style>
<script>
function hl_thema() {
    if(thema.style.backgroundColor == "transparent") {
        document.getElementById("thema").style.backgroundColor = "orange";
  }
  else {
        document.getElementById("thema").style.backgroundColor = "transparent";
  }
}
 
function hl_etim() {
      // if(document.getElementsByClassName("etim")[0].style.backgroundColor == "transparent") { Si introduzco esto
      // que es lo que necesito para volver a poner transparente el fondo, la cosa no funciona
      x = document.getElementsByClassName("etim");
      var i;
      for (i = 0; i < x.length; i++) {
        x[i].style.backgroundColor = "turquoise";
  }
}
</script>
</head>
<body>
<button onclick="hl_thema()">Destacar un solo fragmento</button>
<p> En este ejemplo, <span id="thema" style="background:transparent">Este es el texto a destacar. </span>. El resto no hace falta. Y si se vuelve a apretar se vuelve transparente.</p>
<p> Con un solo fragmento a destacar basta utilizar 'span id' y 'getElementbyId', pero al tener más de un texto a resaltar hay que utilizar
'getElementsbyClassName', que no funciona con 'id' y funciona con 'class'.
<p>Por lo tanto, al clicar <button onclick="hl_etim()">Destacar nombres que empiezan por A</button>, utilizando 'GetElementsbyClassName' y 'span class'
me tendría que funcionar igual, no? Por ejemplo para destacar los nombres que empiezen por A de una lista como 'José, <span class="etim">Andrés</span>, Laura, <span class="etim">Alberto</span>,
María, <span class="etim">Aurora</span>. Pero ahora al volver a apretar no se vuelve transparente</p>
</body>
</html>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar
sin imagen de perfil
Val: 10
Ha aumentado su posición en 10 puestos en JavaScript (en relación al último mes)
Gráfica de JavaScript

deshacer cambio de backgroundColor onclick

Publicado por deo (23 intervenciones) el 03/03/2016 22:37:31
Creo que si funciona, pero habías olvidado el if/else..............

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>prova_js</title>
<style>span.etim {background:transparent};</style>
<script>
function hl_thema() {
if(thema.style.backgroundColor == "transparent") {
document.getElementById("thema").style.backgroundColor = "orange";
}
else {
document.getElementById("thema").style.backgroundColor = "transparent";
}
}
 
function hl_etim() {
// if(document.getElementsByClassName("etim")[0].style.backgroundColor == "transparent") { Si introduzco esto
// que es lo que necesito para volver a poner transparente el fondo, la cosa no funciona
x = document.getElementsByClassName("etim");
var i;
for (i = 0; i < x.length; i++) {
//x[i].style.backgroundColor = "turquoise";                   //<<<<<   ????  if/else?
//console.log("x["+i+"]."+ x[i].style.backgroundColor); // << para VER en Consola: con F12 en Firefox
 
if(x[i].style.backgroundColor == "transparent") {
	x[i].style.backgroundColor = "orange";
	}
	else {
	x[i].style.backgroundColor = "transparent";
	}
}
}
</script>
</head>
<body>
<button onclick="hl_thema()">Destacar un solo fragmento</button>
<p> En este ejemplo, <span id="thema" style="background:transparent">Este es el texto a destacar. </span>. El resto no hace falta. Y si se vuelve a apretar se vuelve transparente.</p>
<p> Con un solo fragmento a destacar basta utilizar 'span id' y 'getElementbyId', pero al tener más de un texto a resaltar hay que utilizar
'getElementsbyClassName', que no funciona con 'id' y funciona con 'class'.
<p>Por lo tanto, al clicar <button onclick="hl_etim()">Destacar nombres que empiezan por A</button>, utilizando 'GetElementsbyClassName' y 'span class'
me tendría que funcionar igual, no?
Por ejemplo para destacar los nombres que empiezen por A de una lista como 'José,
<span class="etim">Andrés</span>, Laura, 
<span class="etim">Alberto</span>,
María, <span class="etim">Aurora</span>. 
Pero ahora al volver a apretar no se vuelve transparente</p>
</body>
</html>
Valora esta respuesta
Me gusta: Está respuesta es útil y esta claraNo me gusta: Está respuesta no esta clara o no es útil
0
Comentar