jQuery滚动到元素

我有这个input元素:

 <input type="text" class="textfield" value="" id="subject" name="subject"> 

然后我还有一些其他元素,如其他文本input,textareas等

当用户用#subject单击该input时,页面应该以良好的animation滚动到页面的最后一个元素。 它应该是一个滚动到底部,而不是顶部。

该页面的最后一个项目是一个submitbutton与#submit

 <input type="submit" class="submit" id="submit" name="submit" value="Ok, Done."> 

animation不应该太快,应该是stream畅的。

我正在运行最新的jQuery版本。 我更喜欢不安装任何插件,而是使用默认的jQueryfunction来实现这一点。

假设你有一个带有id button ,试试这个例子:

 $("#button").click(function() { $('html, body').animate({ scrollTop: $("#elementtoScrollToID").offset().top }, 2000); }); 

我从文章中获得了代码, 无需jQuery插件即可顺利滚动到一个元素 。 我已经在下面的例子中进行了testing。

 <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> 

jQuery .scrollTo()方法

jQuery .scrollTo(): 查看 – 演示,API,来源

我写了这个轻量级的插件,使页面/元素滚动更容易。 这是灵活的,你可以传入一个目标元素或指定的值。 也许这可能是jQuery的下一个正式版本的一部分,你怎么看?


示例用法:

 $('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 

选项:

scrollTarget :指示期望滚动位置的元素,string或数字。

offsetTop :定义滚动目标上方额外间距的数字。

持续时间 :确定animation运行时间的string或数字。

easing :一个string,指示哪个缓动函数用于转换。

完成 :animation完成后调用的函数。

如果你对平滑的滚动效果不太感兴趣,只是想滚动到特定的元素,你不需要一些jQuery的function。 Javascript已经得到你的情况覆盖:

https://developer.mozilla.org/en-US/docs/Web/API/element.scrollIntoView

所以你需要做的是: $("selector").get(0).scrollIntoView();

.get(0)是因为我们想检索JavaScript的DOM元素而不是JQuery的DOM元素。

查看ScrollTo插件。 你可以在这里看到演示。

我希望它有帮助。

 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> 

使用这个简单的脚本

 if($(window.location.hash).length > 0){ $('html, body').animate({ scrollTop: $(window.location.hash).offset().top}, 1000); } 

如果在url中find了一个哈希标签,那么scrollTo就会生成该ID的animation。 如果找不到哈希标记,则忽略该脚本。

史蒂夫和彼得的解决scheme工作得很好。

但在某些情况下,您可能必须将该值转换为整数。 奇怪的是,从$("...").offset().top返回的值有时是float
使用: parseInt($("....").offset().top)

例如:

 $("#button").click(function() { $('html, body').animate({ scrollTop: parseInt($("#elementtoScrollToID").offset().top) }, 2000); }); 

紧凑版本的“animation”解决scheme。

 $.fn.scrollTo = function (speed) { if (typeof(speed) === 'undefined') speed = 1000; $('html, body').animate({ scrollTop: parseInt($(this).offset().top) }, speed); }; 

基本用法: $('#your_element').scrollTo();

如果只处理滚动到input元素,则可以使用focus() 。 例如,如果你想滚动到第一个可见的input:

 $(':input:visible').first().focus(); 

或者类的.error容器中的第一个可见input:

 $('.error :input:visible').first().focus(); 

感谢Tricia Ball指出这一点!

使用这个解决scheme,您不需要任何插件,除了在closures</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); } 

在加载时,如果地址中存在散列,则滚动到该地址。

而且 – 无论何时你点击一个带有href散列a链接(例如#top ,我们都会滚动到它。

在大多数情况下,最好使用插件。 认真。 我要在这里吹我的 。 当然也有其他的。 但是请检查一下,如果他们真的避免了你想要一个插件的陷阱 – 不是所有的人都这样做。

我已经写了关于在其他地方使用插件的原因。 简而言之,这里的大多数答案都是基础

 $('html, body').animate( { scrollTop: $target.offset().top }, duration ); 

是坏的UX。

  • animation不响应用户操作。 即使用户点击,点击或尝试滚动,它也会继续。

  • 如果animation的起点接近目标元素,则animation非常缓慢。

  • 如果目标元素放置在页面底部附近,则无法滚动到窗口的顶部。 滚动animation然后突然中止。

为了处理这些问题(和其他一些问题 ),你可以使用我的插件, jQuery.scrollable 。 电话就变成了

 $( window ).scrollTo( targetPosition ); 

就是这样。 当然,还有更多的select 。

关于目标位置,在大多数情况下, $target.offset().top完成这项工作。 但请注意,返回的值没有考虑html元素的边框( 请参阅此演示 )。 如果您在任何情况下都需要目标位置准确,最好使用

 targetPosition = $( window ).scrollTop() + $target[0].getBoundingClientRect().top; 

即使设置了html元素的边框,这也是有效的。

这是我的方法抽象的ID和HREF的,使用一个通用的类select器

 $(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> 
 var scrollTo = function($parent, $element) { var topDiff = $element.position().top - $parent.position().top; $parent.animate({ scrollTop : topDiff }, 100); }; 

非常简单易用的自定义jQuery插件。 只需将scroll=属性添加到可单击的元素,并将其值设置为您要滚动的select器即可。

像这样: <a scroll="#product">Click me</a> 。 它可以在任何元素上使用。

 (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> 
 $('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); 

要显示完整元素(如果可以使用当前窗口大小):

 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); 

我写了一个通用函数,滚动到jQuery对象,CSSselect器或数值。

用法示例:

 // 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"); 

该函数的代码:

 /** * 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, eg * 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); }; 

当用户用#subject单击该input时,页面应该以良好的animation滚动到页面的最后一个元素。 它应该是一个滚动到底部,而不是顶部。

该页面的最后一个项目是一个带有#submit的提交button

 $('#subject').click(function() { $('#submit').focus(); $('#subject').focus(); }); 

这将首先向下滚动到#submit然后将光标恢复到被单击的input,模仿向下滚动,并在大多数浏览器上工作。 它也不需要jQuery,因为它可以用纯JavaScript编写。

这种使用focusfunction的方式能否通过链接focus调用以更好的方式模拟animation。 我没有testing过这个理论,但是看起来像这样:

 <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> 

对于什么是值得的,这是我如何设法实现这种行为的一般元素,可以在一个DIV内滚动。 在我们的例子中,我们不滚动整个正文,而只是用溢出的特定元素:auto; 在一个更大的布局。

它会创build目标元素高度的虚假input,然后将重点放在该元素上,而且无论您在滚动层次结构中有多深,浏览器都会关心其余部分。 奇迹般有效。

 var $scrollTo = $('#someId'), inputElem = $('<input type="text"></input>'); $scrollTo.prepend(inputElem); inputElem.css({ position: 'absolute', width: '1px', height: $scrollTo.height() }); inputElem.focus(); inputElem.remove(); 

$('html, body').animate(...)不适合iphone,android chrome Safari浏览器。

我必须定位页面的根内容元素。

$( '#cotnent')。animation(…)

这是我结束了

 if (navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) { $('#content').animate({ scrollTop: $("#elementtoScrollToID").offset().top }, 'slow'); } else{ $('html, body').animate({ scrollTop: $("#elementtoScrollToID").offset().top }, 'slow'); } 

所有的主体内容都与#content div联系起来

 <html> .... <body> <div id="content"> .... </div> </body> </html> 

animation:

 // 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 }); }); 

我设置了一个模块scroll-element npm install scroll-element 。 它是这样工作的:

 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) 

写在以下SOpost的帮助下:

  • 偏移顶级的一个元件,而无需-jquery的

  • scrollTop的animation,而无需-的jQuery

这里是代码:

 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 } } 

如果你想在一个溢出容器(而不是上面的$('html, body')回答)中滚动,也可以使用绝对定位,这是要做的:

 var elem = $('#myElement'), container = $('#myScrollableContainer'), pos = elem.position().top + container.scrollTop() - container.position().top; container.animate({ scrollTop: pos } 

简单的方法来实现页面的滚动目标div ID

 var targetOffset = $('#divID').offset().top; $('html, body').animate({scrollTop: targetOffset}, 1000);