2011-12-19 9 views
10

En mi aplicación puedo abrir varias cajas div que se superponen entre sí. Al hacer clic en un cuadro, ese cuadro debe moverse a la parte superior. Cuál es la mejor manera de lograr esto?Cambiando el índice z para hacer que un clic aparezca en la parte superior

Lo único que se me ocurre es recorrer todos los cuadros de valores de índice Z para obtener el valor más alto, y luego agregar 1 a ese valor y aplicarlo en el div en el que se hace clic.

¿Algún consejo para mí?

+0

Código, figura, ¡cualquier cosa nos ayuda a entender lo que quieres! Simplemente no puedo entender cómo puedo hacer clic en el cuadro si ese cuadro está detrás de otro cuadro. ¡o tiene que ser que se muestren partes de esos cuadros! –

Respuesta

14

algo como esto debería hacerlo:

// Set up on DOM-ready 
$(function() { 
    // Change this selector to find whatever your 'boxes' are 
    var boxes = $("div"); 

    // Set up click handlers for each box 
    boxes.click(function() { 
     var el = $(this), // The box that was clicked 
      max = 0; 

     // Find the highest z-index 
     boxes.each(function() { 
      // Find the current z-index value 
      var z = parseInt($(this).css("z-index"), 10); 
      // Keep either the current max, or the current z-index, whichever is higher 
      max = Math.max(max, z); 
     }); 

     // Set the box that was clicked to the highest z-index plus one 
     el.css("z-index", max + 1); 
    }); 
}); 
+0

Solución interesante. Pero, ¿por qué estás usando parseInt en este caso? Gracias por la respuesta, por cierto! – holyredbeard

+1

¡seguro! utilicé 'parseInt' porque llamar $(). css (" z-index ") va a devolver el índice z del elemento como una cadena, pero necesitamos un número para pasar a Math.max. – keeganwatkins

+1

en realidad, 'Math.max()' convertirá cadenas a números automáticamente, pero el valor predeterminado para elementos sin un índice z explícito es 'auto' que devolverá 'NaN' cuando se pase a' Math.max() ' – keeganwatkins

4

me acercaría esto haciendo un plugin de jQuery, por lo que no tiene que preocuparse acerca de la configuración manualmente el hacer el seguimiento z-index y del más alto valor a una variable:

(function() { 
    var highest = 1; 

    $.fn.bringToTop = function() { 
     this.css('z-index', ++highest); // increase highest by 1 and set the style 
    }; 
})(); 

$('div.clickable').click(function() { 
    $(this).bringToTop(); 
}); 

Esto no funcionaría bien si configura z-index con cualquier otro código en su página.

+2

Desarrollé este código un poco más https://github.com/dangayle/jQuery-z-index –

0

se podría hacer algo como esto con jQuery:.

$ ('# div') haga clic en (function() {$ (this) css ('zIndex', '10000'});

esto funcionará siempre que el índice z para todos los divs subyacentes sea inferior a 10000. O bien, podría escribir una función para iterar todos los divs y obtener el índice z más alto y mover el clic al número +1.

0

Creo que su idea de obtener el índice z más alto es el camino a seguir.

Sin embargo, en lugar de recorrer cada clic, recorro una sola vez la carga de la página y mantengo un objeto que almacena el índice z más alto.

CONSTANTS = { 
    highest_z_index = 0; 
}; 

function getHighestZ(){ 
    var $divs = $('div'); 

    $.each($divs,function(){ 
     if (this.css('z-index') > CONSTANTS.highest_z_index){ 
      CONSTANTS.highest_z_index = this.css('z-index'); 
     } 
    }); 
} 

getHighestZ(); 

$('#YourDiv').click(function(){ 
    if (CONSTANTS.highest_z_index > $(this).css('z-index'){ 
     $(this).css('z-index',++CONSTANTS.highest_z_index); 
    } 
}); 
5

suponiendo que tiene elementos con una clase específica ("caja" en mi ejemplo) y que todos están en el mismo contenedor como esto:

<div> 
    <div class="box"></div> 
    <div class="box"></div> 
    <div class="box"></div> 
</div> 

Asumiendo que tiene el css correcta:

.box {position:absolute; z-index:10} 

puede utilizar el código del jQuery js a continuación:

$('.box').click(function() { 
    // set ohters element to the initial level 
    $(this).siblings('.box').css('z-index', 10); 
    // set clicked element to a higher level 
    $(this).css('z-index', 11); 
}); 
Cuestiones relacionadas