Foros del Web » Programando para Internet » Javascript »

Superposición de capas (¡Urgente!)

Estas en el tema de Superposición de capas (¡Urgente!) en el foro de Javascript en Foros del Web. ¡Hola a todos! Soy nueva en esta web de foros, a menudo buscando información por internet sobre programación web he llegado a este sitio y ...
  #1 (permalink)  
Antiguo 16/11/2009, 11:29
Avatar de joss23  
Fecha de Ingreso: noviembre-2009
Mensajes: 16
Antigüedad: 14 años, 5 meses
Puntos: 0
Superposición de capas (¡Urgente!)

¡Hola a todos!

Soy nueva en esta web de foros, a menudo buscando información por internet sobre programación web he llegado a este sitio y me ha parecido muy completo, así que desde hace algun tiempo le tengo hechado el ojo, y hoy he decidido registrarme .

Bueno, ahí va mi primera consulta:

Estoy haciendo una pequeña web y en una de las páginas necesito que, al hacer click sobre un botón, aparezcan dos capas, con una imagen cada una, superpuestas, es decir, de forma que solo se visualice la última capa llamada, y la primera quede escondida detrás. He utilizado la propiedad z-index para posicionar las capas en "profundidad" y un script de java para llamar las capas (showLayerNumber()) al hacer click sobre el botón (que de momento es un texto simple). El problema es que, al presionar el botón aparecen una detrás de la otra y en el orden correcto, pero al cabo de unos segundos estas capas intercambian solas sus posiciones, de forma que la que estaba detrás pasa a ponerse delante, y luego vuelve a su posición inicial. Este intercambio (que a veces es un "parpadeo" y otras veces dura unos segundos) se va repitiendo indefinidamente cada pocos segundos y sin haber tocado nada más que el botón la primera vez. He estado estudiando el código pero mis conocimientos en programación aun son reducidos.

¿Alguien sabría como solucionarlo?


Otro problema que tengo es que, cada una de las imágenes que hay en esas mismas capas tiene un enlace con la función de esconder la capa a la que pertenece (hideLayerNumber()), una vez se han escondido ambas capas, al hacer clic en el botón, no aparecen de nuevo.

¿Qué podría hacer para que se pudieran esconder y volver mostrar varias veces?



Aquí dejo el código básico completo:

Código HTML:
<html>
<head>

<SCRIPT LANGUAGE="JavaScript"> 	//Define global variables
	
	var layerNumShowing=1;

	
	function init(){

       	  if (navigator.appName == "Netscape") {

		    layerStyleRef="layer.";

 			layerRef="document.layers";

			styleSwitch="";

			}else{

 			layerStyleRef="layer.style.";

			layerRef="document.all";

 			styleSwitch=".style";

			} 	}



	function showLayerNumber(number){

 		var layerNumToShow=number;
		
		showLayer(eval('"layer' + layerNumToShow+'"')); }
		

	
	function hideLayerNumber(number){

 		var layerNumToHide=number;

		hideLayer(eval('"layer' + layerNumToHide+'"')); }




	function showLayer(layerName){

 		eval(layerRef+'["'+layerName+'"]'+styleSwitch+'.visibility="visible"'); 	} 	



	function hideLayer(layerName){

 		eval(layerRef+'["'+layerName+'"]'+styleSwitch+'.visibility="hidden"'); 	} 


	function showCapa(nomber){

 		if (nomber == 1) {

		showLayerNumber(2);
				
		showLayerNumber(1);  }
		 
		
		else { alert("O") } }


 </script>



<style type="text/css">
 
 #layer1 {position: absolute; z-index: 2; visibility: hidden; left: 50px; top: 300px;}

 #layer2 {position: absolute; z-index: 1; visibility: hidden; left: 15px; top: 200px;}

 #loopControls {position: any; visibility: visible;}

</style>



</head>


<body onLoad="init()">

<div id="loopControls">

<p><a href="javascript:showCapa(1)">BOTÓN</a>

</div>

  
<!-- CONTENIDOS DE LOS LAYERS -->

<!--layer 1-->

	<div id="layer1">

  <map name="FPMap0">
  <area href="javascript:hideLayerNumber(1)" shape="rect" coords="1054, 106, 1196, 138"></map>
  <img border="0" dynsrc="imagen1.jpg" width="1230" height="630" usemap="#FPMap0">   
 	
 	</div>

<!--layer 2--> 	

<div id="layer2">
   
 <map name="FPMap1">
 <area href="javascript:hideLayerNumber(2)" shape="rect" coords="1055, 399, 1199, 428"></map>
 <img border="0" dynsrc="imagen2.jpg" width="1230" height="630" usemap="#FPMap1">

 	</div>


</body>

</html> 


Espero haber sabido explicarme...jaja

¡Muchas gracias!
  #2 (permalink)  
Antiguo 16/11/2009, 12:21
Avatar de Adler
Colaborador
 
Fecha de Ingreso: diciembre-2006
Mensajes: 4.671
Antigüedad: 17 años, 4 meses
Puntos: 126
Respuesta: Superposición de capas (¡Urgente!)

Hola

Esta superposición de capas la monté ya hace algún tiempo y no recuerdo si funciona en todos los navegadores

Código javascript:
Ver original
  1. <html>
  2. <head>
  3. <script type="text/javascript">
  4. var ns4 = (document.layers)? true:false
  5. var ie4 = (document.all)? true:false
  6. var ns6 = (document.getElementById)? true:false
  7. var nivel = 1;
  8. var PosElementoAlto = 0 ;
  9. var Arr = [];
  10.  
  11. var info = {
  12. captura_objeto : function(idnombre) {
  13.     if (ns6)
  14.     {
  15.     return document.getElementById(idnombre);
  16.     }
  17.     else if (ie4)
  18.     {
  19.     return document.all[idnombre];
  20.     }
  21.     else if (ns4)
  22.     {
  23.     return document.layers[idnombre];
  24.     }
  25.     else
  26.     {
  27.     return null;
  28.     }
  29. },
  30.  
  31.  
  32. Evento : function(elemento,nomevento,funcion) {
  33.     if (elemento.attachEvent)
  34.     {
  35.         var fct=function(){
  36.             funcion.call(elemento,window.event);
  37.         }
  38.         elemento.attachEvent('on'+nomevento,fct);
  39.         return true;
  40.     }
  41.     else  
  42.         if (elemento.addEventListener)
  43.         {
  44.         elemento.addEventListener(nomevento,funcion,false);
  45.         return true;
  46.         }
  47.         else
  48.         return false;
  49. },
  50.  
  51.  
  52. init: function(){
  53. var ref = info.captura_objeto('lasLigas').getElementsByTagName('A');
  54.     for (var i = 0; i < ref.length; i++) {
  55. var infodiv = info.captura_objeto('info_menu_'+ref[i].id);
  56.         if (document.Element || document.body) {
  57.             info.altura = infodiv.scrollHeight;
  58.         } else {
  59.             info.altura = infodiv.clientHeight;
  60.         }
  61.             infodiv.style.display = 'none';
  62.             infodiv.style.zIndex = 0;
  63.                     info.Evento(ref[i], 'click', function() {info.efecto_largo(this.id)});
  64.     }
  65. },
  66.  
  67.  
  68. PosicionAbsolutaElemento: function(element)  {
  69. var window_height =  parseInt(((screen.height) / 2) - info.altura);
  70. var window_width = parseInt(((screen.width) / 2) - 150);
  71.  
  72.     if (typeof element == "string")
  73.         element = info.captura_objeto(element)
  74.             if (!element) return { top:0,left:0 };
  75. var y = 0;
  76. var x = 0;
  77.             while (element.offsetParent) {
  78.                     x += element.offsetLeft;
  79.                     y += element.offsetTop;
  80.                 element = element.offsetParent;
  81.      }
  82.     return {top:y, left:x, height:window_height, width: window_width};
  83.  
  84. },
  85.  
  86.    
  87. efecto_largo: function(id){
  88.             if(info.captura_objeto('info_menu_'+id).style.display == 'none'){
  89.                     clearInterval(info.intervalo);
  90.                 info.despliega_largo(id);
  91.         info.abierto_largo = false;
  92. //alert(info.abierto_largo);
  93.             }else{
  94.                     clearInterval(info.intervalo);
  95.                     info.recoge_largo(id);
  96.         info.abierto_largo = true;
  97. //alert(info.abierto_largo);
  98.             }
  99. },
  100.    
  101.  
  102. despliega_largo: function(id){
  103. Arr.unshift(id);
  104. //alert(Arr);
  105.     for (var i = 0; i < Arr.length; i++) {
  106. var infodiv = info.captura_objeto('info_menu_'+Arr[i]);
  107. var PosElemento = info.PosicionAbsolutaElemento(Arr[i]);
  108.         if (i == 0) {
  109. PosElementoAlto = PosElemento.top;
  110.             infodiv.style.height = '1px';
  111.             infodiv.style.display = 'block';
  112.             infodiv.style.zIndex = nivel;
  113.             infodiv.style.left = parseInt(PosElemento.width) +'px';
  114.             infodiv.style.top = parseInt(PosElemento.height - PosElementoAlto) +'px';
  115.                     info.intervalo = setInterval(function(){ info.redimenciona_largo(info.altura,id); }, 1);
  116.             nivel ++;
  117. //alert(parseInt(PosElementoAlto))
  118.         } else {
  119. var izq_arr = parseInt(20 * i) 
  120.             infodiv.style.left = parseInt(PosElemento.width - izq_arr) +'px';
  121.             infodiv.style.top = parseInt((PosElemento.height) - (PosElementoAlto + izq_arr)) +'px';
  122.         }
  123.     }
  124. },
  125.    
  126.  
  127. recoge_largo: function(id){
  128. //alert(id)
  129. var infodiv = info.captura_objeto('info_menu_'+id);
  130. var i, encaja;
  131.     for (i = 0; i < Arr.length; i++) {
  132.         if (Arr[i] == id) {
  133.                 encaja = i;
  134.     break;
  135.         }
  136.     }
  137.     for (var j = 0; j < Arr.length; j++) {
  138.         if (j > encaja ) {
  139. var infodiv2 = info.captura_objeto('info_menu_'+Arr[j]);
  140. var PosElemento = info.PosicionAbsolutaElemento('info_menu_'+Arr[j]);
  141.             infodiv2.style.left = parseInt(PosElemento.left + 20) +'px';
  142.             infodiv2.style.top = parseInt(PosElemento.top + 20) +'px';
  143.  
  144.         }
  145.     }
  146.     Arr.splice(encaja, 1);
  147.             infodiv.style.height = info.altura + 'px';
  148.     info.intervalo = setInterval(function(){ info.redimenciona_largo(0,id); }, 1);
  149. },
  150.    
  151.  
  152. redimenciona_largo: function(limite,id){
  153. var infodiv = info.captura_objeto('info_menu_'+id);
  154.     inicial = parseInt(infodiv.style.height);
  155.             actual = Math.ceil((limite - inicial) / 4);
  156.             inicial += actual;
  157.             infodiv.style.height = inicial + 'px';
  158.         if (parseInt(inicial) >= (limite - 5) && parseInt(inicial) <= (limite + 5)) {
  159.             if (info.abierto_largo == false) {
  160.                 infodiv.style.height = limite + 'px';
  161.                 clearInterval(info.intervalo);
  162.             } else {
  163.                 infodiv.style.height = '0px';
  164.                 infodiv.style.display = 'none';
  165.                 clearInterval(info.intervalo);
  166.             }
  167.         }
  168. },
  169.    
  170.  
  171. z_Index : function(id){
  172. // RECOGER
  173. var infodiv = info.captura_objeto('info_menu_'+id);
  174. var i, encaja;
  175.     for (i = 0; i < Arr.length; i++) {
  176.         if (Arr[i] == id) {
  177.                 encaja = i;
  178.     break;
  179.         }
  180.     }
  181. //alert(encaja);
  182.     for (var j = 0; j < Arr.length; j++) {
  183.         if (j > encaja) {
  184. var infodiv2 = info.captura_objeto('info_menu_'+Arr[j]);
  185. var PosElemento = info.PosicionAbsolutaElemento('info_menu_'+Arr[j]);
  186.             infodiv2.style.left = parseInt(PosElemento.left + 20) +'px';
  187.             infodiv2.style.top = parseInt(PosElemento.top + 20) +'px';
  188.  
  189.         }
  190.     }
  191.     Arr.splice(encaja, 1);
  192.  
  193.  
  194. //MOSTRAR
  195. Arr.unshift(id);
  196.  
  197.     for (var i = 0; i < Arr.length; i++) {
  198. var PosElemento = info.PosicionAbsolutaElemento(Arr[i]);
  199. var infodiv = info.captura_objeto('info_menu_'+Arr[i]);
  200. //if (PosElemento.top == 0) PosElemento.top = 9;
  201.         if (i == 0) {
  202.             infodiv.style.zIndex = nivel;
  203.             infodiv.style.left = parseInt(PosElemento.width) +'px';
  204.             infodiv.style.top = parseInt(PosElemento.height - (PosElemento.top + PosElementoAlto)) +'px';
  205.             nivel ++;
  206. //alert(parseInt(PosElementoAlto))
  207.         } else {
  208. //var infodiv = info.captura_objeto('info_menu_'+Arr[i]);
  209. var izq_arr = parseInt(20 * i)
  210.             infodiv.style.left = parseInt(PosElemento.width - izq_arr) +'px';
  211.             infodiv.style.top = parseInt(PosElemento.height - (PosElementoAlto + izq_arr)) +'px';
  212.         }
  213.     }
  214. },
  215.  
  216. abierto_largo : true,
  217. abierto_ancho : true
  218. }
  219.  
  220. info.Evento(window, 'load', info.init);
  221. </script>
  222. </head>
  223. <body>
  224. <div id="lasLigas">
  225. <a href="javascript:void(0);" id="1">MOTOCICLETAS</a> ||
  226. <a href="javascript:void(0);" id="2">COCHES</a> ||
  227. <a href="javascript:void(0);" id="3">AVIONES</a> ||
  228. <a href="javascript:void(0);" id="4">BARCOS</a>
  229. </div>
  230.  
  231. <div id="info_menu_1" style="position:absolute; left:0px; top:0px; height:0px; width:400px; overflow:hidden; font:bold 10px Verdana, Helvetica, sans-serif; background-color:#FFFFFF; border: 1px solid #C9C9C9; border-width: 1px 1px 1px 1px;">
  232. <span style="float:right;"><a href="#" onclick="info.z_Index(1)" title="Traer al Frente"><></a> || <a href="#" onclick="info.efecto_largo(1)" title="Cierra">X</a></span> MUESTRAS DE MOTOCICLETAS<br /><br />
  233. Un texto que quiero ocultar y mostrar con el botón 1<br />
  234. Un texto que quiero ocultar y mostrar con el botón 1<br />
  235. </div>
  236.  
  237.  
  238. <div id="info_menu_2" style="position:absolute; left:0px; top:0px; height:0px; width:400px; overflow:hidden; font:bold 10px Verdana, Helvetica, sans-serif; background-color:#FFFFFF; border: 1px solid #C9C9C9; border-width: 1px 1px 1px 1px;">
  239. <span style="float:right;"><a href="#" onclick="info.z_Index(2)" title="Traer al Frente"><></a> || <a href="#" onclick="info.efecto_largo(2)" title="Cierra">X</a></span> MUESTRAS DE COCHES<br /><br />
  240. Un texto que quiero ocultar y mostrar con el botón 2<br />
  241. Un texto que quiero ocultar y mostrar con el botón 2<br />
  242. </div>
  243.  
  244.  
  245. <div id="info_menu_3" style="position:absolute; left:0px; top:0px; height:0px; width:400px; overflow:hidden; font:bold 10px Verdana, Helvetica, sans-serif; background-color:#FFFFFF; border: 1px solid #C9C9C9; border-width: 1px 1px 1px 1px;">
  246. <span style="float:right;"><a href="#" onclick="info.z_Index(3)" title="Traer al Frente"><></a> || <a href="#" onclick="info.efecto_largo(3)" title="Cierra">X</a></span> MUESTRAS DE AVIONES<br /><br />
  247. Un texto que quiero ocultar y mostrar con el botón 3<br />
  248. Un texto que quiero ocultar y mostrar con el botón 3
  249. </div>
  250.  
  251.  
  252. <div id="info_menu_4" style="position:absolute; left:0px; top:0px; height:0px; width:400px; overflow:hidden; font:bold 10px Verdana, Helvetica, sans-serif; background-color:#FFFFFF; border: 1px solid #C9C9C9; border-width: 1px 1px 1px 1px;">
  253. <span style="float:right;"><a href="#" onclick="info.z_Index(4)" title="Traer al Frente"><></a> || <a href="#" onclick="info.efecto_largo(4)" title="Cierra">X</a></span> MUESTRAS DE BARCOS<br /><br />
  254. Un texto que quiero ocultar y mostrar con el botón 4<br />
  255. Un texto que quiero ocultar y mostrar con el botón 4<br />
  256. </div>
  257. </body>
  258. </html>

Suerte
__________________
Los formularios se envían/validan con un botón Submit
<input type="submit" value="Enviar" style="background-color:#0B5795; font:bold 10px verdana; color:#FFF;" />
  #3 (permalink)  
Antiguo 19/11/2009, 12:06
Avatar de joss23  
Fecha de Ingreso: noviembre-2009
Mensajes: 16
Antigüedad: 14 años, 5 meses
Puntos: 0
Respuesta: Superposición de capas (¡Urgente!)

Muchas gracias por tu código, Adler.
La verdad es que estoy buscando algo bastante más sencillo, sin el efecto de despliegue ni el desplazamiento de una capa al abrirse otra, pero me lo guardo porque es posible que me sirva en otro momento, ¡muchas gracias!
Por cierto, lo he probado con Internet, Netscape y Mozilla pero solo me ha funcionado con el primero...


Si no puedo resolverlo dentro del código que puse seguramente haré algo que se me ha ocurrido con las variables...

Si alguien tiene alguna idea más se la agradecería mucho
  #4 (permalink)  
Antiguo 20/11/2009, 05:39
Avatar de Adler
Colaborador
 
Fecha de Ingreso: diciembre-2006
Mensajes: 4.671
Antigüedad: 17 años, 4 meses
Puntos: 126
Respuesta: Superposición de capas (¡Urgente!)

Hola

Cita:
Iniciado por joss23 Ver Mensaje
Por cierto, lo he probado con Internet, Netscape y Mozilla pero solo me ha funcionado con el primero...
Por un momento me has puesto en duda. Funciona tanto en IE8 como FF, Opera y Chrome
__________________
Los formularios se envían/validan con un botón Submit
<input type="submit" value="Enviar" style="background-color:#0B5795; font:bold 10px verdana; color:#FFF;" />
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:03.