2012-02-14 17 views
32

Como puede ver en la imagen siguiente, hay "A", "B", "C", "D" y "E" en el sitio web, y el usuario solo puede ver A, B y un poco partes de D en su navegador. Deben requerir desplazarse hacia abajo en el navegador o algunos usuarios pueden tener una pantalla más grande o una ventana más larga en su navegador que les permita ver incluso el elemento C.¿Puedo detectar el área visible del usuario en el navegador?

Ok, mi pregunta es, ¿es posible dejar esto? ¿Sabes lo que el usuario ve en su navegador usando javascript? En este elemento, es "A", "B" y "D".

enter image description here

+0

Puede consultar [http: // stackoverflow.com/questions/704758/how-to-check-if-an-element-is-really-visible-with-javascript] (http://stackoverflow.com/questions/704758/how-to-check-if-an -element-is-really-visible-with-javascript) para respuestas a una pregunta similar. – Bill

Respuesta

11

Pruébalo :) http://jsfiddle.net/Aj2fU/5/

$('input').click(function(){ 
    // check for visible divs with class 'check' 
    $('.check').each(function(){ 
     var pos = $(this).offset(), 
      wX = $(window).scrollLeft(), wY = $(window).scrollTop(), 
      wH = $(window).height(), wW = $(window).width(), 
      oH = $(this).outerHeight(), oW = $(this).outerWidth(); 

     // check the edges 
     // left, top and right, bottom are in the viewport 
     if (pos.left >= wX && pos.top >= wY && 
      oW + pos.left <= wX + wW && oH + pos.top <= wY + wH) 
      alert('Div #' + $(this).attr('id') + ' is fully visible'); 
     else // partially visible 
     if (((pos.left <= wX && pos.left + oW > wX) || 
      (pos.left >= wX && pos.left <= wX + wW)) && 
      ((pos.top <= wY && pos.top + oH > wY) || 
      (pos.top >= wY && pos.top <= wY + wH))) 
      alert('Div #' + $(this).attr('id') + ' is partially visible'); 
     else // not visible 
      alert('Div #' + $(this).attr('id') + ' is not visible'); 
    });   
});​ 

Actualizado trabajar con divs muy amplios. Básicamente, verifica si los bordes izquierdo, superior y derecho, inferior de los divs se encuentran en la parte visible de la pantalla, parcialmente o fuera de la ventana gráfica.

+0

Gran respuesta, ¿hay alguna manera de adaptar esto para calcular el número de píxeles a la vista, cuando un elemento está parcialmente a la vista? Hice una pregunta similar aquí http://stackoverflow.com/questions/28685693/get-the-number-of-an-elements-pixels-which- are -inside-the-viewport – tripRev

+0

@tripRev no es un problema, tome una Desplazamiento horizontal de la vista, reste el borde izquierdo del objeto. Dirá cuánto del objeto está oculto a la izquierda. Restarlo del ancho total del objeto y encontrar la diferencia entre el resultado y el ancho de la vista. Indicará si el objeto se muestra por completo o solo una parte de él (que es, obviamente, el ancho de la vista). Repita lo mismo para la dirección vertical. – Cheery

3

Puede obtener área visible de la ventana,

var pwidth = $(window).width(); 
var pheight = $(window).height(); 

a continuación, obtener el documento de desplazamiento,

$(document).scroll(function(e) { 
     var top = $(this).scrollTop();  
     $("h1").html("total visible area is from:"+ top +" to "+ (pheight + top) +"px"); 
    }); 

Ejemplo completo está aquí: http://jsfiddle.net/parag1111/kSaNp/

+0

He creado un ejemplo de trabajo de la misma. http://jsfiddle.net/parag1111/kSaNp/1/ –

4

Básicamente, usted' d primero tiene que medir la ventana dimentio ns, al usar el objeto ventana, entonces necesitaría recorrer cada uno de los elementos que desea verificar y calcular si encajan.

Vea esto jsfiddle para un ejemplo.

Aquí está el código (para la posteridad):

HTML:

<div id="info"> 
    <p class="wxh"></p> 
    <p class="txl"></p> 
    <p class="report"></p> 
</div> 

<h1>A big list!</h1> 
<ul></ul> 

CSS:

#info{ 
    position: fixed; 
    right: 0px; 
    text-align: center; 
    background: white; 
    border: 2px solid black; 
    padding: 10px; 
} 

JS:

$(function(){ 

    $(window).bind('scroll.measure resize.measure',function(){ 

     // Gather together the window width, height, and scroll position. 
     var winWidth = $(window).width(), 
      winHeight = $(window).height(), 
      winLeft = $(window).scrollLeft(), 
      winTop = $(window).scrollTop(), 
      winBottom = winTop + winHeight, 
      winRight = winLeft + winWidth, 
      inView = []; 

     // Loop over each of the elements you want to check 
     $('.inview').each(function(){ 

      // Get the elements position and dimentions. 
      var pos = $(this).position(), 
       width = $(this).outerWidth(), 
       height = $(this).outerHeight(); 

      // Set bottom and right dimentions. 
      pos.bottom = pos.top + height; 
      pos.right = pos.left + width; 

      // Check whether this element is partially within 
      // the window's visible area. 
      if((
       pos.left >= winLeft && 
       pos.top >= winTop && 
       pos.right <= winRight && 
       pos.bottom <= winBottom 
      ) || (
       pos.left >= winLeft && pos.top >= winTop && 
       pos.left <= winRight && pos.top <= winBottom 
      ) || (
       pos.right <= winRight && pos.bottom <= winBottom && 
       pos.right >= winLeft && pos.bottom >= winTop 
      )){ 
       // Change this to push the actual element if you need it. 
       inView.push($(this).text()); 
      } 
     }); 

     // For the purposes of this example, we only need the 
     // first and last element, but in your application you may need all. 
     var first = inView.shift(), 
      last = inView.pop(); 

     // Show the details in the info box. 
     $('#info .wxh').text(winWidth+' x '+winHeight); 
     $('#info .txl').text(winTop+' x '+winLeft); 
     $('#info .report').text('Showing from '+first+' to '+last); 
    }); 

    // The rest is just setup stuff, to make the area scrollable. 
    for(var i=0; i<100; i++){ 
     $('ul').append('<li class="inview">List item '+i+'</li>'); 
    } 

    $(window).trigger('resize.measure'); 
}) ​ 
12

Usando lo siguiente, puede obtener el tamaño de la ventana del navegador.

window.innerHeight; 
window.innerWidth; 

http://bit.ly/zzzVUv - Tuvimos que usar la caché de Google como el sitio no se carga para mí. la página original: http://www.javascripter.net/faq/browserw.htm

Si desea detectar hasta qué punto han desplazado por la página, puede utilizar

window.scrollX; // Horizontal scrolling 
window.scrollY; // Vertical scrolling 

Además, he encontrado un objeto de la ventana - window.screen. En mi sistema tiene los datos siguientes:

window.screen.availHeight = 994; 
window.screen.availLeft = 0; 
window.screen.availTop = 0; 
window.screen.availWidth = 1280; 
window.screen.colorDepth = 32; 
window.screen.height = 1280; 
window.screen.pixelDepth = 32; 
window.screen.width = 1280; 

Espero que estos respondan a su pregunta lo suficiente.

Cuestiones relacionadas