paginas gratis español descargar como caracteristicas actualizar activar javascript cross-browser scroll

gratis - javascript español



Método de navegador cruzado para determinar el porcentaje de desplazamiento vertical en Javascript (10)

¿Cómo puedo averiguar qué porcentaje de la barra de desplazamiento vertical ha movido un usuario en un punto dado?

Es bastante fácil atrapar el evento ''onscroll'' para disparar cuando el usuario se desplaza hacia abajo de la página, pero ¿cómo puedo averiguar dentro de ese evento qué tan lejos se han desplazado? En este caso, el porcentaje en particular es lo importante. No estoy especialmente preocupado por una solución para IE6.

¿Alguno de los principales frameworks (Dojo, jQuery, Prototype, Mootools) expone esto de una manera simple y compatible con varios navegadores?

Aclamaciones,


Esto debería ser el truco, no se requieren bibliotecas:

function currentScrollPercentage() { return ((document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight) * 100); }


Si está usando Dojo, puede hacer lo siguiente:

var vp = dijit.getViewport(); return (vp.t / (document.documentElement.scrollHeight - vp.h));

Que devolverá un valor entre 0 y 1.


Usando jQuery

$(window).scrollTop();

obtendrá la posición de desplazamiento, luego podrá calcular a partir de qué porcentaje se basa en la altura de la ventana.

También hay una propiedad estándar de DOM scrollTop que puedes usar como document.body.scrollTop pero no estoy seguro de cómo se comporta esto en el navegador, supongo que si hay inconsistencias, el método de jQuery las tiene en cuenta.


Esta pregunta ha estado aquí durante mucho tiempo, lo sé, pero me tropecé con ella al tratar de resolver el mismo problema. Así es como lo resolví, en jQuery:

Primero, envolví lo que quería desplazar en un div (no semántico, pero ayuda). Luego configure el desbordamiento y la altura en el contenedor.

<div class="content-wrapper" style="overflow: scroll; height:100px"> <div class="content">Lot of content that scrolls</div> </div>

Finalmente, pude calcular el% de desplazamiento de estas métricas:

var $w = $(this), scroll_top = $w.scrollTop(), total_height = $w.find(".content").height(), viewable_area = $w.height(), scroll_percent = Math.floor((scroll_top + viewable_area) / total_height * 100);

Aquí hay un violín con un ejemplo de trabajo: http://jsfiddle.net/prEGf/


Creo que encontré una buena solución que no depende de ninguna biblioteca:

/** * Get current browser viewpane heigtht */ function _get_window_height() { return window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0; } /** * Get current absolute window scroll position */ function _get_window_Yscroll() { return window.pageYOffset || document.body.scrollTop || document.documentElement.scrollTop || 0; } /** * Get current absolute document height */ function _get_doc_height() { return Math.max( document.body.scrollHeight || 0, document.documentElement.scrollHeight || 0, document.body.offsetHeight || 0, document.documentElement.offsetHeight || 0, document.body.clientHeight || 0, document.documentElement.clientHeight || 0 ); } /** * Get current vertical scroll percentage */ function _get_scroll_percentage() { return ( (_get_window_Yscroll() + _get_window_height()) / _get_doc_height() ) * 100; }


Me funcionaron perfectamente en Chrome 19.0, FF12, IE9:

function getElementScrollScale(domElement){ return domElement.scrollTop / (domElement.scrollHeight - domElement.clientHeight); } function setElementScrollScale(domElement,scale){ domElement.scrollTop = (domElement.scrollHeight - domElement.clientHeight) * scale; }


var maxScrollTop = messages.get(0).scrollHeight - messages.height(); var scroll = messages.scrollTop() / maxScrollTop; // [0..1]


Encontré una manera de corregir una respuesta anterior, por lo que funciona en todos los casos. Probado en Chrome, Firefox y Safari.

(((document.documentElement.scrollTop + document.body.scrollTop) / (document.documentElement.scrollHeight - document.documentElement.clientHeight) || 0) * 100)


Primero adjunte un oyente de eventos a algún documento que desee mantener al día

yourDocument.addEventListener("scroll", documentEventListener, false);

Entonces:

function documentEventListener(){ var currentDocument = this; var docsWindow = $(currentDocument.defaultView); // This is the window holding the document var docsWindowHeight = docsWindow.height(); // The viewport of the wrapper window var scrollTop = $(currentDocument).scrollTop(); // How much we scrolled already, in the viewport var docHeight = $(currentDocument).height(); // This is the full document height. var howMuchMoreWeCanScrollDown = docHeight - (docsWindowHeight + scrollTop); var percentViewed = 100.0 * (1 - howMuchMoreWeCanScrollDown / docHeight); console.log("More to scroll: "+howMuchMoreWeCanScrollDown+"pixels. Percent Viewed: "+percentViewed+"%"); }


Oct 2016: arreglado. Los paréntesis en la demostración de jsbin faltaban en la respuesta. Oops.

Chrome, Firefox, IE9 +. Demostración en vivo en jsbin

var h = document.documentElement, b = document.body, st = ''scrollTop'', sh = ''scrollHeight''; var percent = (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100;

Como función:

function getScrollPercent() { var h = document.documentElement, b = document.body, st = ''scrollTop'', sh = ''scrollHeight''; return (h[st]||b[st]) / ((h[sh]||b[sh]) - h.clientHeight) * 100; }

Si prefiere jQuery (respuesta original):

$(window).on(''scroll'', function(){ var s = $(window).scrollTop(), d = $(document).height(), c = $(window).height(); var scrollPercent = (s / (d - c)) * 100; console.clear(); console.log(scrollPercent); })

html{ height:100%; } body{ height:300%; }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>