Foros del Web

Foros del Web (http://www.forosdelweb.com/)
-   Javascript (http://www.forosdelweb.com/f13/)
-   -   Como obtener dinamicamente el siguiente nivel con JS (http://www.forosdelweb.com/f13/como-obtener-dinamicamente-siguiente-nivel-con-js-765613/)

junihh 31/12/2009 01:51

Como obtener dinamicamente el siguiente nivel con JS
 
Hola señores

En AS2, si quiero obtener el siguiente nivel de una pelicula o clip de pelicula (movieclip), escribo la siguiente linea:

Código:

elmovieclip.getNextHighestDepth();
Eso me devuelve el valor numerico del siguiente nivel disponible, para evitar que si uso un nivel similar en dos objetos generados dinamicamente, se borre accidentalmente el objeto antiguo sustituido por otro nuevo.

Me gustaria aplicar algo similar a un script que estoy preparando en JS que genera dinamicamente tres layers, ya que por el momento estoy poniendo manualmente los niveles en los que se deben crear. Existe algo que se asemeje en JS al metodo usado en AS2 ??

Gracias anticipadas a cualquier informacion, enlace o ayuda que me puedan ofrecer.

kreativodesigns 31/12/2009 03:31

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
a que te refieres con niveles?

junihh 31/12/2009 07:55

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
Niveles o levels. Toma como ejemplo a Photoshop o Illustrator. Ambos usan capas (layers) y para lograr que un objeto se vea delante de otro, solo sobrepones las capas y listo. Cada capa es independiente de la otra y nunca se juntan a menos que uses la opcion "Fusionar capas".

Es eso. En Flash, cuando generamos objetos dinamicamente es obligatorio asignarle a cada objeto un nivel de capa distinto a los anteriores, porque como mencione, dos objetos con el mismo nivel de capa se reemplazan.

Solo necesito saber si existe algo similar a "getNextHighestDepth()" para asignar un numero de capa distinto automaticamente a "objeto.style.zIndex". Entiendo que puede ser confuso para quien no sepa AS2, asi que espero haberme explicado esta vez.

kreativodesigns 31/12/2009 08:09

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
no te sirve el asignarle como tu dices al z-index distintos valores?

Adler 31/12/2009 08:42

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
Hola

A ver si es lo que "buscas"

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. Un texto que quiero ocultar y mostrar con el botón 1
  236. </div>
  237.  
  238.  
  239. <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;">
  240. <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 />
  241. Un texto que quiero ocultar y mostrar con el botón 2<br />
  242. Un texto que quiero ocultar y mostrar con el botón 2<br />
  243. Un texto que quiero ocultar y mostrar con el botón 2
  244. </div>
  245.  
  246.  
  247. <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;">
  248. <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 />
  249. Un texto que quiero ocultar y mostrar con el botón 3<br />
  250. Un texto que quiero ocultar y mostrar con el botón 3
  251. </div>
  252.  
  253.  
  254. <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;">
  255. <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 />
  256. Un texto que quiero ocultar y mostrar con el botón 4<br />
  257. Un texto que quiero ocultar y mostrar con el botón 4<br />
  258. Un texto que quiero ocultar y mostrar con el botón 4
  259. </div>
  260. </body>
  261. </html>

Suerte

junihh 31/12/2009 08:53

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
@kreativodesigns: La pregunta de si hay un metodo para aplicar un valor automatico es para evitar hacerlo manual, que es el metodo que estoy usando ahora.

@Adler: Mucho codigo para algo tan simple :-)

Creo que me vere forzado a usar la forma como aplicaba los niveles cuando me inicie con Flash: elnivel++;

Gracias a ambos por sus ideas y ayuda.

buzu 31/12/2009 09:05

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
Javascript no tiene un método para obtener el siguiente nivel. En actionscript eso es muy útil por que puedes hacer muchas cosas sin preocuparte que un elemento tenga cierta nivel que sea inferior a otro elemento y por lo tanto que quede detras de ese otro elemento en caso de que se superpongan. Afortunadamente el Javascript podemos simular dicho comportamiento sin necesidad de hacer tanto circo.
Cuando escribes HTML, el elemento que aparece al final del documento, es el elemento con nivel más alto, por lo que lo único que tendrías que hacer es mover el elemento que quieres que tenga el nivel más alto al final del documento. Esto sirve siempre y cuando no modifiques directamente el z-index de ningún otro elemento.
En caso de que tengas que modificar el z-index de algun otro elemento, lo que tendrías que hacer es objeto que te lleve un record sobre los z-index de los elementos. Esto te va a agilizar mucho las cosas, en comparación con tener que estar obteniendo el z-index de cada elemento cada que necesites calcular el nivel más alto.

Panino5001 31/12/2009 09:26

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
Es bastante diferente a actionScript (donde tampoco es muy recomendable usar getNextHighestDepth, mejor usar DepthManager, pero claro, es cuestión de gustos).
En javascript, sólo los elementos posicionados con propiedad position diferentes a static son susceptibles de manejar z-index (zIndex para javascript). Además, el valor máximo de z-index varía para los diferentes navegadores: http://softwareas.com/whats-the-maximum-z-index.
Otra cuestión a considerar para poder acceder a los valores de z-index es si se definieron con el atributo style o si se definieron en hojas de estilo o tags style. Si se definieron con style podrías acceder a su valor con elemento.style, pero si no, tandrías que usar los estilos computados (getComputedStyle o currentStyle para explorer).
Pero en general, podrías usar algo como esto para emular esa funcionalidad:
Código PHP:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<
html xmlns="http://www.w3.org/1999/xhtml">
<
head>
<
meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<
title>Documento sin t&iacute;tulo</title>
<
style>
#dd{ position:absolute; z-index:200}
</style>
<
script>
function 
css(o,prop){
    if(
window.getComputedStyle){
        return 
document.defaultView.getComputedStyle(o,null).getPropertyValue(prop);
    }else{
        var 
re = /(-([a-z]){1})/g;
        if (
prop == 'float'prop 'styleFloat';
        if (
re.test(prop)) {
            
prop prop.replace(re, function () {
                return 
arguments[2].toUpperCase();
            });
        }
        return 
o.currentStyle[prop] ? o.currentStyle[prop] : null;
    }
}  
function 
getNextHighestDepth(){
    var 
col=document.getElementsByTagName('*'),l=col.length,i,mx=0,t;
    for(
i=0;i<l;i++){
        
t=parseInt(css(col[i],'z-index'));
        if(
&& t>mx)
            
mx=t;
    }
    return 
mx+1;
}
onload=function(){
    
alert(getNextHighestDepth());
}
</script>
</head>

<body>
<div id="pp" style="position:absolute; z-index:100">Colocar aquí el contenido para  id "pp"</div>
<div id="dd">Colocar aquí el contenido para  id "dd"</div>
<p>nada</p>

</body>
</html> 


Panino5001 31/12/2009 09:33

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
Edito: igualmente, escucha a Buzu (:adios:) que tiene mucha razón acerca de lo del rendimiento.

junihh 31/12/2009 10:09

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
@buzu: Estoy preparando un script que crea tres capas para mostrar mensajes de alerta: Un div con fondo negro-transparente, un div con el mensaje de alerta y finalmente una imagen como boton de cerrar. Crei que estaba obligado a aplicar el zIndex, pero luego de probar lo que mencionas que siempre el ultimo elemento en la pagina es el de mayor posicion, veo que realmente no es necesario el zIndex. De plano lo quite :-)

@Panino5001: Los elementos que mencione a @buzu son creados dinamicamente y no uso CSS preescrito, la apariencia de los div la aplico directamente via la funcion. De todos modos esas funciones que pones estan muy interesantes, asi que si no te molesta las querre tener guardadas por ahi si en algun momento mas adelante las necesito.

Muchisimas gracias por sus respuestas porque me han servido bastante.

junihh 31/12/2009 10:15

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
Disculpen por olvidar algo importante: Feliz año para todos :-)

buzu 31/12/2009 15:28

Respuesta: Como obtener dinamicamente el siguiente nivel con JS
 
Pues como te decía, no es necesario tanto circo. Algunas veces es mejor saber como trabaja HTMl y el DOM. Yo generalmente no uso z-index, pero puede resultar muy útil. Por ejemplo, sin el z-index hacer algo como lo que hago en http://imbuzu.wordpress.com/2009/12/...en-javascript/ sería más laborioso.

Por otro lado, estar acá para ver la función de panino (Hola amigo) ha sido muy educativo. Aun que tiene el problemilla que te comentaba sobre rendimiento, y más por que el DOM es una pesadilla cuando se trata de rendimiento.

Feliz año a todos.

Amigo Panino, un placer coincidir después de tanto tiempo.


La zona horaria es GMT -6. Ahora son las 06:44.

Desarrollado por vBulletin® Versión 3.8.7
Derechos de Autor ©2000 - 2026, Jelsoft Enterprises Ltd.