ejemplos color animate javascript jquery animation scroll jquery-animate

javascript - color - Desplácese suavemente al elemento específico en la página



jquery animate scrolltop (7)

Desplazamiento suave: mira ma no jQuery

Basado en un artículo en itnewb.com, hice una demostración de desplazamiento sin problemas para desplazarse sin bibliotecas externas.

El javascript es bastante simple. Primero, una función auxiliar para mejorar el soporte del navegador cruzado para determinar la posición actual.

function currentYPosition() { // Firefox, Chrome, Opera, Safari if (self.pageYOffset) return self.pageYOffset; // Internet Explorer 6 - standards mode if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6, 7 and 8 if (document.body.scrollTop) return document.body.scrollTop; return 0; }

Luego, una función para determinar la posición del elemento de destino, aquella a la que nos gustaría desplazarnos.

function elmYPosition(eID) { var elm = document.getElementById(eID); var y = elm.offsetTop; var node = elm; while (node.offsetParent && node.offsetParent != document.body) { node = node.offsetParent; y += node.offsetTop; } return y; }

Y la función central para hacer el desplazamiento

function smoothScroll(eID) { var startY = currentYPosition(); var stopY = elmYPosition(eID); var distance = stopY > startY ? stopY - startY : startY - stopY; if (distance < 100) { scrollTo(0, stopY); return; } var speed = Math.round(distance / 100); if (speed >= 20) speed = 20; var step = Math.round(distance / 25); var leapY = stopY > startY ? startY + step : startY - step; var timer = 0; if (stopY > startY) { for ( var i=startY; i<stopY; i+=step ) { setTimeout("window.scrollTo(0, "+leapY+")", timer * speed); leapY += step; if (leapY > stopY) leapY = stopY; timer++; } return; } for ( var i=startY; i>stopY; i-=step ) { setTimeout("window.scrollTo(0, "+leapY+")", timer * speed); leapY -= step; if (leapY < stopY) leapY = stopY; timer++; } return false; }

Para llamarlo, simplemente haz lo siguiente. Crea un enlace que apunta a otro elemento utilizando el ID como referencia para un ancla de destino .

<a href="#anchor-2" onclick="smoothScroll(''anchor-2'');">smooth scroll to the headline with id anchor-2<a/> ... ... some content ... <h2 id="anchor-2">Anchor 2</h2>

Derechos de autor

En el pie de página de itnewb.com se escribe lo siguiente: The techniques, effects and code demonstrated in ITNewb articles may be used for any purpose without attribution (although we recommend it) (2014-01-12)

Quiero tener 4 botones / enlaces al principio de la página, y debajo de ellos el contenido.

En los botones coloco este código:

<a href="#idElement1">Scroll to element 1</a> <a href="#idElement2">Scroll to element 2</a> <a href="#idElement3">Scroll to element 3</a> <a href="#idElement4">Scroll to element 4</a>

Y debajo de los enlaces habrá contenido:

<h2 id="idElement1">Element1</h2> content.... <h2 id="idElement2">Element2</h2> content.... <h2 id="idElement3">Element3</h2> content.... <h2 id="idElement4">Element4</h2> content....

Está funcionando ahora, pero no puede hacer que se vea más suave.

Usé este código, pero no puedo hacerlo funcionar.

$(''html, body'').animate({ scrollTop: $("#elementID").offset().top }, 2000);

¿Alguna sugerencia? Gracias.

Editar: y el violín: http://jsfiddle.net/WxJLx/2/


Super suavemente con requestAnimationFrame

Para la animación de desplazamiento procesada sin problemas, se puede usar window.requestAnimationFrame() que se comporta mejor con rendering que las soluciones setTimeout() normales.

Un ejemplo básico se ve así. Se requiere un step función para cada fotograma de animación del navegador y permite una mejor gestión del tiempo de repintado y, por lo tanto, aumenta el rendimiento.

function doScrolling(elementY, duration) { var startingY = window.pageYOffset var diff = elementY - startingY var start // Bootstrap our animation - it will get called right before next frame shall be rendered. window.requestAnimationFrame(function step(timestamp) { if (!start) start = timestamp // Elapsed miliseconds since start of scrolling. var time = timestamp - start // Get percent of completion in range [0, 1]. var percent = Math.min(time / duration, 1) window.scrollTo(0, startingY + diff * percent) // Proceed with animation as long as we wanted it to. if (time < duration) { window.requestAnimationFrame(step) } }) }

Para la posición Y del elemento, use funciones en otras respuestas o la que aparece en mi violín que se menciona a continuación.

Configuré una función un poco más sofisticada con soporte de facilitación y desplazamiento adecuado a los elementos más bajos: https://jsfiddle.net/s61x7c4e/


Desplazamiento suave con jQuery.ScrollTo

Para utilizar el plugin jQuery ScrollTo, debe hacer lo siguiente

  1. Crear enlaces donde href apunta a otros elementos.id
  2. crea los elementos a los que quieres desplazarte
  3. referencia jQuery y el complemento scrollTo
  4. Asegúrese de agregar un controlador de evento de clic para cada enlace que debe hacer un desplazamiento suave

Creando los enlaces

<h1>Smooth Scrolling with the jQuery Plugin .scrollTo</h1> <div id="nav-list"> <a href="#idElement1">Scroll to element 1</a> <a href="#idElement2">Scroll to element 2</a> <a href="#idElement3">Scroll to element 3</a> <a href="#idElement4">Scroll to element 4</a> </div>

Al crear los elementos de destino aquí solo se muestran los dos primeros, los demás títulos se configuran de la misma manera. Para ver otro ejemplo, agregué un enlace a la navegación a.toNav

<h2 id="idElement1">Element1</h2> .... <h2 id="idElement1">Element1</h2> ... <a class="toNav" href="#nav-list">Scroll to Nav-List</a>

Establecer las referencias a los scripts. Su ruta a los archivos puede ser diferente.

<script src="./jquery-1.8.3.min.js"></script> <script src="./jquery.scrollTo-1.4.3.1-min.js"></script>

Cableado todo

El código siguiente está tomado del plugin jQuery easing

jQuery(function ($) { $.easing.elasout = function (x, t, b, c, d) { var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3; if (a < Math.abs(c)) { a = c; var s = p / 4; } else var s = p / (2 * Math.PI) * Math.asin(c / a); // line breaks added to avoid scroll bar return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b; }; // important reset all scrollable panes to (0,0) $(''div.pane'').scrollTo(0); $.scrollTo(0); // Reset the screen to (0,0) // adding a click handler for each link // within the div with the id nav-list $(''#nav-list a'').click(function () { $.scrollTo(this.hash, 1500, { easing: ''elasout'' }); return false; }); // adding a click handler for the link at the bottom $(''a.toNav'').click(function () { var scrollTargetId = this.hash; $.scrollTo(scrollTargetId, 1500, { easing: ''elasout'' }); return false; }); });

Demostración completamente funcional en plnkr.co

Puede echar un vistazo al código de soucre para la demostración.

Actualización mayo de 2014

Basado en otra pregunta encontré otra solución de kadaj . Aquí jQuery animate se usa para desplazarse a un elemento dentro de un <div style=overflow-y: scroll>

$(document).ready(function () { $(''.navSection'').on(''click'', function (e) { debugger; var elemId = ""; //eg: #nav2 switch (e.target.id) { case "nav1": elemId = "#s1"; break; case "nav2": elemId = "#s2"; break; case "nav3": elemId = "#s3"; break; case "nav4": elemId = "#s4"; break; } $(''.content'').animate({ scrollTop: $(elemId).parent().scrollTop() + $(elemId).offset().top - $(elemId).parent().offset().top }, { duration: 1000, specialEasing: { width: ''linear'' , height: ''easeOutBounce'' }, complete: function (e) { //console.log("animation completed"); } }); e.preventDefault(); }); });


Acabo de hacer esta solución solo de javascript a continuación.

Uso simple:

EPPZScrollTo.scrollVerticalToElementById(''signup_form'', 20);

Objeto del motor (puede virar con filtro, valores fps):

/** * * Created by Borbás Geri on 12/17/13 * Copyright (c) 2013 eppz! development, LLC. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ var EPPZScrollTo = { /** * Helpers. */ documentVerticalScrollPosition: function() { if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari. if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode). if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8. return 0; // None of the above. }, viewportHeight: function() { return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; }, documentHeight: function() { return (document.height !== undefined) ? document.height : document.body.offsetHeight; }, documentMaximumScrollPosition: function() { return this.documentHeight() - this.viewportHeight(); }, elementVerticalClientPositionById: function(id) { var element = document.getElementById(id); var rectangle = element.getBoundingClientRect(); return rectangle.top; }, /** * Animation tick. */ scrollVerticalTickToPosition: function(currentPosition, targetPosition) { var filter = 0.2; var fps = 60; var difference = parseFloat(targetPosition) - parseFloat(currentPosition); // Snap, then stop if arrived. var arrived = (Math.abs(difference) <= 0.5); if (arrived) { // Apply target. scrollTo(0.0, targetPosition); return; } // Filtered position. currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter); // Apply target. scrollTo(0.0, Math.round(currentPosition)); // Schedule next tick. setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps)); }, /** * For public use. * * @param id The id of the element to scroll to. * @param padding Top padding to apply above element. */ scrollVerticalToElementById: function(id, padding) { var element = document.getElementById(id); if (element == null) { console.warn(''Cannot find element with id /'''+id+''/'.''); return; } var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding; var currentPosition = this.documentVerticalScrollPosition(); // Clamp. var maximumScrollPosition = this.documentMaximumScrollPosition(); if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition; // Start animation. this.scrollVerticalTickToPosition(currentPosition, targetPosition); } };


He estado usando esto por mucho tiempo:

function scrollToItem(item) { var diff=(item.offsetTop-window.scrollY)/8 if (Math.abs(diff)>1) { window.scrollTo(0, (window.scrollY+diff)) clearTimeout(window._TO) window._TO=setTimeout(scrollToItem, 30, item) } else { window.scrollTo(0, item.offsetTop) } }

uso: scrollToItem(element) donde el element es document.getElementById(''elementid'') por ejemplo.


Variación de @tominko respuesta. Una animación un poco más suave y un problema resuelto con setTimeout () invocado infinitamente, cuando algunos elementos no pueden alinearse a la parte superior de la ventana gráfica.

function scrollToItem(item) { var diff=(item.offsetTop-window.scrollY)/20; if(!window._lastDiff){ window._lastDiff = 0; } console.log(''test'') if (Math.abs(diff)>2) { window.scrollTo(0, (window.scrollY+diff)) clearTimeout(window._TO) if(diff !== window._lastDiff){ window._lastDiff = diff; window._TO=setTimeout(scrollToItem, 15, item); } } else { console.timeEnd(''test''); window.scrollTo(0, item.offsetTop) } }