jQuery przewiń do elementu
Mam ten input
element:
<input type="text" class="textfield" value="" id="subject" name="subject">
Potem mam kilka innych elementów, jak inne wejścia tekstowe, tekstowe itp.
Gdy użytkownik kliknie na input
z #subject
, strona powinna przewijać do ostatniego elementu strony z ładną animacją. Powinno to być przewijanie do dołu, a nie do góry.
Ostatnim elementem strony jest przycisk submit
z #submit
:
<input type="submit" class="submit" id="submit" name="submit" value="Ok, Done.">
Animacja nie powinna być zbyt szybka i płynna.
Uruchamiam najnowszy jQuery wersja. Wolę nie instalować żadnych wtyczek, ale używać domyślnych funkcji jQuery, aby to osiągnąć.
25 answers
Zakładając, że masz przycisk o id button
, wypróbuj ten przykład:
$("#button").click(function() {
$([document.documentElement, document.body]).animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 2000);
});
Dostałem kod z Artykułu płynne przewijanie do elementu bez wtyczki jQuery. I Przetestowałem go na poniższym przykładzie.
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
$(document).ready(function (){
$("#click").click(function (){
$('html, body').animate({
scrollTop: $("#div1").offset().top
}, 2000);
});
});
</script>
<div id="div1" style="height: 1000px; width 100px">
Test
</div>
<br/>
<div id="div2" style="height: 1000px; width 100px">
Test 2
</div>
<button id="click">Click me</button>
</html>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-08 14:48:17
JQuery .scrollTo (): View-Demo, API, Source
Napisałem ten lekki plugin, aby Strona / element przewijania znacznie łatwiejsze. Jest elastyczny, gdy można przekazać element docelowy lub określoną wartość. Może to będzie część następnego oficjalnego wydania jQuery, co o tym sądzisz?
Przykłady Użycia:
$('body').scrollTo('#target'); // Scroll screen to target element
$('body').scrollTo(500); // Scroll screen 500 pixels down
$('#scrollable').scrollTo(100); // Scroll individual element 100 pixels down
Opcje:
scrollTarget : element, łańcuch lub liczba wskazująca żądaną pozycję przewijania.
offsetTop : liczba określająca dodatkowe odstępy nad celem przewijania.
Czas trwania: ciąg znaków lub liczba określająca czas trwania animacji.
easing : łańcuch znaków wskazujący, której funkcji easing użyć do przejścia.
complete : funkcja do wywołania po zakończeniu animacji.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-17 10:37:03
Jeśli nie interesuje Cię efekt płynnego przewijania, a po prostu chcesz przewijać do określonego elementu, nie potrzebujesz do tego funkcji jQuery. Javascript ma Twoją sprawę pod kontrolą:
Https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView
Więc wszystko, co musisz zrobić, to: $("selector").get(0).scrollIntoView();
.get(0)
jest używany, ponieważ chcemy odzyskać element Dom JavaScript, a nie element DOM jQuery.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-21 06:19:32
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-12 06:42:35
Używanie tego prostego skryptu
if($(window.location.hash).length > 0){
$('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000);
}
Spowoduje, że jeśli w adresie url zostanie znaleziony znacznik hash, scrollTo animuje ID. Jeśli nie znaleziono znacznika hash, zignoruj skrypt.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-24 04:34:21
jQuery(document).ready(function($) {
$('a[href^="#"]').bind('click.smoothscroll',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate( {
'scrollTop': $target.offset().top-40
}, 900, 'swing', function () {
window.location.hash = target;
} );
} );
} );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul role="tablist">
<li class="active" id="p1"><a href="#pane1" role="tab">Section 1</a></li>
<li id="p2"><a href="#pane2" role="tab">Section 2</a></li>
<li id="p3"><a href="#pane3" role="tab">Section 3</a></li>
</ul>
<div id="pane1"></div>
<div id="pane2"></div>
<div id="pane3"></div>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-16 05:08:51
Rozwiązanie Steve ' a i Petera działa bardzo dobrze.
Ale w niektórych przypadkach może być konieczna Konwersja wartości na liczbę całkowitą. Co dziwne, wartość zwracana z $("...").offset().top
jest czasami w float
.
Użycie: parseInt($("....").offset().top)
Na przykład:
$("#button").click(function() {
$('html, body').animate({
scrollTop: parseInt($("#elementtoScrollToID").offset().top)
}, 2000);
});
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-27 06:03:00
Kompaktowa wersja rozwiązania "animate".
$.fn.scrollTo = function (speed) {
if (typeof(speed) === 'undefined')
speed = 1000;
$('html, body').animate({
scrollTop: parseInt($(this).offset().top)
}, speed);
};
Użycie Podstawowe: $('#your_element').scrollTo();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-22 07:28:57
Jeśli zajmujesz się tylko przewijaniem do elementu wejściowego, możesz użyć focus()
. Na przykład, jeśli chcesz przewinąć do pierwszego widocznego wejścia:
$(':input:visible').first().focus();
Lub pierwsze widoczne wejście w kontenerze z klasą .error
:
$('.error :input:visible').first().focus();
Podziękowania dlaTricii Ball za zwrócenie na to uwagi!
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:02:47
Z To rozwiązanie nie potrzebujesz żadnej wtyczki i jest nie jest wymagana konfiguracja poza umieszczeniem skryptu przed zamknięciem znacznika </body>
.
$("a[href^='#']").on("click", function(e) {
e.preventDefault();
$("html, body").animate({
scrollTop: $($(this).attr("href")).offset().top
}, 1000);
});
if ($(window.location.hash).length > 1) {
$("html, body").animate({
scrollTop: $(window.location.hash).offset().top
}, 1000);
}
Po załadowaniu, jeśli w adresie jest hash, przewijamy do niego.
I-za każdym razem, gdy klikniesz link a
z Hashem href
np. #top
, przewijamy do niego.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-10-20 17:37:56
W większości przypadków najlepiej byłoby użyć wtyczki. Poważnie. Mam zamiar tout mój tutaj . Oczywiście, że są też inni. Ale proszę sprawdzić, czy naprawdę unikają pułapek, dla których chcesz wtyczki w pierwszej kolejności - nie wszystkie z nich.
Pisałem o powodach używania wtyczki gdzie indziej . W skrócie, the one liner u podstaw większości odpowiedzi tutaj
$('html, body').animate( { scrollTop: $target.offset().top }, duration );
Jest zły UX.
Animacja nie odpowiada użytkownikowi działania. Trwa nawet wtedy, gdy użytkownik kliknie, dotknie lub spróbuje przewijać.
Jeśli punkt początkowy animacji znajduje się blisko elementu docelowego, animacja jest boleśnie powolna.
Jeśli element docelowy znajduje się u dołu strony, nie można go przewijać na górę okna. Animacja przewijania zatrzymuje się nagle, w średnim ruchu.
Aby rozwiązać te problemy (i } kilka innych), możesz użyć wtyczki moje, jQuery.scrollable . Następnie wywołanie staje się
$( window ).scrollTo( targetPosition );
I to wszystko. Oczywiście istnieje więcej opcji .
W odniesieniu do pozycji docelowej, $target.offset().top
wykonuje zadanie w większości przypadków. Należy jednak pamiętać, że zwracana wartość nie uwzględnia obramowania elementu html
(zobacz to demo ). Jeśli pozycja docelowa musi być dokładna w każdych okolicznościach, lepiej użyć
targetPosition = $( window ).scrollTop() + $target[0].getBoundingClientRect().top;
To działa nawet jeśli obramowanie na html
element jest ustawiony.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-08-17 11:43:44
Oto moje podejście do abstrakcji ID i href, używając ogólnego selektora klas
$(function() {
// Generic selector to be used anywhere
$(".js-scroll-to").click(function(e) {
// Get the href dynamically
var destination = $(this).attr('href');
// Prevent href=“#” link from changing the URL hash (optional)
e.preventDefault();
// Animate scroll to destination
$('html, body').animate({
scrollTop: $(destination).offset().top
}, 500);
});
});
<!-- example of a fixed nav menu -->
<ul class="nav">
<li>
<a href="#section-1" class="nav-item js-scroll-to">Item 1</a>
</li>
<li>
<a href="#section-2" class="nav-item js-scroll-to">Item 2</a>
</li>
<li>
<a href="#section-3" class="nav-item js-scroll-to">Item 3</a>
</li>
</ul>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-21 16:46:37
Bardzo prosta i łatwa w użyciu niestandardowa wtyczka jQuery. Wystarczy dodać atrybut scroll=
do klikalnego elementu i ustawić jego wartość w selektorze, do którego chcesz przewijać.
W ten sposób: <a scroll="#product">Click me</a>
. Może być stosowany na każdym elemencie.
(function($){
$.fn.animateScroll = function(){
console.log($('[scroll]'));
$('[scroll]').click(function(){
selector = $($(this).attr('scroll'));
console.log(selector);
console.log(selector.offset().top);
$('html body').animate(
{scrollTop: (selector.offset().top)}, //- $(window).scrollTop()
1000
);
});
}
})(jQuery);
// RUN
jQuery(document).ready(function($) {
$().animateScroll();
});
// IN HTML EXAMPLE
// RUN ONCLICK ON OBJECT WITH ATTRIBUTE SCROLL=".SELECTOR"
// <a scroll="#product">Click To Scroll</a>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-31 16:32:57
var scrollTo = function($parent, $element) {
var topDiff = $element.position().top - $parent.position().top;
$parent.animate({
scrollTop : topDiff
}, 100);
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-07-03 06:27:36
Animacje:
// slide to top of the page
$('.up').click(function () {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
// slide page to anchor
$('.menutop b').click(function(){
//event.preventDefault();
$('html, body').animate({
scrollTop: $( $(this).attr('href') ).offset().top
}, 600);
return false;
});
// Scroll to class, div
$("#button").click(function() {
$('html, body').animate({
scrollTop: $("#target-element").offset().top
}, 1000);
});
// div background animate
$(window).scroll(function () {
var x = $(this).scrollTop();
// freezze div background
$('.banner0').css('background-position', '0px ' + x +'px');
// from left to right
$('.banner0').css('background-position', x+'px ' +'0px');
// from right to left
$('.banner0').css('background-position', -x+'px ' +'0px');
// from bottom to top
$('#skills').css('background-position', '0px ' + -x + 'px');
// move background from top to bottom
$('.skills1').css('background-position', '0% ' + parseInt(-x / 1) + 'px' + ', 0% ' + parseInt(-x / 1) + 'px, center top');
// Show hide mtop menu
if ( x > 100 ) {
$( ".menu" ).addClass( 'menushow' );
$( ".menu" ).fadeIn("slow");
$( ".menu" ).animate({opacity: 0.75}, 500);
} else {
$( ".menu" ).removeClass( 'menushow' );
$( ".menu" ).animate({opacity: 1}, 500);
}
});
// progres bar animation simple
$('.bar1').each(function(i) {
var width = $(this).data('width');
$(this).animate({'width' : width + '%' }, 900, function(){
// Animation complete
});
});
$('html, body').animate(...)
nie dla mnie na iPhonie, przeglądarce Android chrome safari.
Musiałem skierować główny element zawartości strony.
$('#cotnent').animate(...)
Oto, z czym skończyłem
if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) {
$('#content').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
else{
$('html, body').animate({
scrollTop: $("#elementtoScrollToID").offset().top
}, 'slow');
}
Cała zawartość ciała połączona z # content div
<html>
....
<body>
<div id="content">
....
</div>
</body>
</html>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-02-06 11:20:01
Łatwy sposób na przewinięcie strony do docelowego identyfikatora div
var targetOffset = $('#divID').offset().top;
$('html, body').animate({scrollTop: targetOffset}, 1000);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-10 13:03:06
$('html, body').animate({scrollTop:
Math.min(
$(to).offset().top-margintop, //margintop is the margin above the target
$('body')[0].scrollHeight-$('body').height()) //if the target is at the bottom
}, 2000);
Aby pokazać pełny element (jeśli jest to możliwe z bieżącym rozmiarem okna):
var element = $("#some_element");
var elementHeight = element.height();
var windowHeight = $(window).height();
var offset = Math.min(elementHeight, windowHeight) + element.offset().top;
$('html, body').animate({ scrollTop: offset }, 500);
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-07-12 06:44:22
Napisałem funkcję ogólnego przeznaczenia, która przewija do obiektu jQuery, selektora CSS lub wartości liczbowej.
Przykładowe użycie:
// scroll to "#target-element":
$.scrollTo("#target-element");
// scroll to 80 pixels above first element with class ".invalid":
$.scrollTo(".invalid", -80);
// scroll a container with id "#my-container" to 300 pixels from its top:
$.scrollTo(300, 0, "slow", "#my-container");
Kod funkcji:
/**
* Scrolls the container to the target position minus the offset
*
* @param target - the destination to scroll to, can be a jQuery object
* jQuery selector, or numeric position
* @param offset - the offset in pixels from the target position, e.g.
* pass -80 to scroll to 80 pixels above the target
* @param speed - the scroll speed in milliseconds, or one of the
* strings "fast" or "slow". default: 500
* @param container - a jQuery object or selector for the container to
* be scrolled. default: "html, body"
*/
jQuery.scrollTo = function (target, offset, speed, container) {
if (isNaN(target)) {
if (!(target instanceof jQuery))
target = $(target);
target = parseInt(target.offset().top);
}
container = container || "html, body";
if (!(container instanceof jQuery))
container = $(container);
speed = speed || 500;
offset = offset || 0;
container.animate({
scrollTop: target + offset
}, speed);
};
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-18 19:46:13
Gdy użytkownik kliknie na to wejście z # subject, strona powinna przewiń do ostatniego elementu strony z ładną animacją. Informatyka powinno być przewijanie do dołu, a nie do góry.
Ostatnim elementem strony jest przycisk submit z # submit
$('#subject').click(function()
{
$('#submit').focus();
$('#subject').focus();
});
Spowoduje to przewinięcie w dół do #submit
, a następnie przywrócenie kursora do klikniętego wejścia, które naśladuje przewinięcie w dół i działa w większości przeglądarek. Nie wymaga również jQuery, ponieważ można go zapisać w czystym JavaScript.
Czy ten sposób używania funkcji focus
może lepiej naśladować animację, poprzez łączenie wywołań focus
. Nie testowałem tej teorii, ale wyglądałaby ona mniej więcej tak:
<style>
#F > *
{
width: 100%;
}
</style>
<form id="F" >
<div id="child_1"> .. </div>
<div id="child_2"> .. </div>
..
<div id="child_K"> .. </div>
</form>
<script>
$('#child_N').click(function()
{
$('#child_N').focus();
$('#child_N+1').focus();
..
$('#child_K').focus();
$('#child_N').focus();
});
</script>
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-11-28 12:34:55
Jeśli to coś warte, w ten sposób udało mi się osiągnąć takie zachowanie dla elementu ogólnego, który może być wewnątrz DIV z przewijaniem. W naszym przypadku nie przewijamy całego ciała, a tylko poszczególne elementy z przepełnieniem: auto; w większym układzie.
Tworzy fałszywy wpis wysokości elementu docelowego, a następnie kładzie na nim nacisk, a przeglądarka zajmie się resztą bez względu na to, jak głęboko w przewijalnej hierarchii jesteś. Działa jak urok.
var $scrollTo = $('#someId'),
inputElem = $('<input type="text"></input>');
$scrollTo.prepend(inputElem);
inputElem.css({
position: 'absolute',
width: '1px',
height: $scrollTo.height()
});
inputElem.focus();
inputElem.remove();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-02-26 11:40:12
Ustawiam Moduł scroll-element npm install scroll-element
. Działa tak:
import { scrollToElement, scrollWindowToElement } from 'scroll-element'
/* scroll the window to your target element, duration and offset optional */
let targetElement = document.getElementById('my-item')
scrollWindowToElement(targetElement)
/* scroll the overflow container element to your target element, duration and offset optional */
let containerElement = document.getElementById('my-container')
let targetElement = document.getElementById('my-item')
scrollToElement(containerElement, targetElement)
Napisane przy pomocy następujących postów:
Oto kod:
export const scrollToElement = function(containerElement, targetElement, duration, offset) {
if (duration == null) { duration = 1000 }
if (offset == null) { offset = 0 }
let targetOffsetTop = getElementOffset(targetElement).top
let containerOffsetTop = getElementOffset(containerElement).top
let scrollTarget = targetOffsetTop + ( containerElement.scrollTop - containerOffsetTop)
scrollTarget += offset
scroll(containerElement, scrollTarget, duration)
}
export const scrollWindowToElement = function(targetElement, duration, offset) {
if (duration == null) { duration = 1000 }
if (offset == null) { offset = 0 }
let scrollTarget = getElementOffset(targetElement).top
scrollTarget += offset
scrollWindow(scrollTarget, duration)
}
function scroll(containerElement, scrollTarget, duration) {
let scrollStep = scrollTarget / (duration / 15)
let interval = setInterval(() => {
if ( containerElement.scrollTop < scrollTarget ) {
containerElement.scrollTop += scrollStep
} else {
clearInterval(interval)
}
},15)
}
function scrollWindow(scrollTarget, duration) {
let scrollStep = scrollTarget / (duration / 15)
let interval = setInterval(() => {
if ( window.scrollY < scrollTarget ) {
window.scrollBy( 0, scrollStep )
} else {
clearInterval(interval)
}
},15)
}
function getElementOffset(element) {
let de = document.documentElement
let box = element.getBoundingClientRect()
let top = box.top + window.pageYOffset - de.clientTop
let left = box.left + window.pageXOffset - de.clientLeft
return { top: top, left: left }
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:10:41
Jeśli chcesz przewijać w kontenerze przelewowym (zamiast odpowiedzi $('html, body')
powyżej), pracując również z pozycjonowaniem absolutnym, jest to sposób:
var elem = $('#myElement'),
container = $('#myScrollableContainer'),
pos = elem.position().top + container.scrollTop() - container.position().top;
container.animate({
scrollTop: pos
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-23 00:11:45
Oto odpowiedź Atharvy z: https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView . Po prostu chcesz dodać, jeśli dokument jest w ramce iframe, możesz wybrać element w ramce nadrzędnej, aby przewijać do widoku:
$('#element-in-parent-frame', window.parent.document).get(0).scrollIntoView();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-22 04:25:31