M P*_*M P 24 javascript jquery animation scroll jquery-animate
我想在页面的开头有4个按钮/链接,在它们下面有内容.
在按钮上我把这个代码:
<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>
Run Code Online (Sandbox Code Playgroud)
在链接下将有内容:
<h2 id="idElement1">Element1</h2>
content....
<h2 id="idElement2">Element2</h2>
content....
<h2 id="idElement3">Element3</h2>
content....
<h2 id="idElement4">Element4</h2>
content....
Run Code Online (Sandbox Code Playgroud)
它现在正在工作,但不能让它看起来更顺畅.
我使用了这段代码,却无法使用它.
$('html, body').animate({
scrollTop: $("#elementID").offset().top
}, 2000);
Run Code Online (Sandbox Code Playgroud)
有什么建议?谢谢.
编辑:和小提琴:http://jsfiddle.net/WxJLx/2/
Dan*_*wka 71
requestAnimationFrame
对于平滑渲染的滚动动画,可以使用window.requestAnimationFrame()
哪种渲染比常规setTimeout()
解决方案更好.
一个基本的例子是这样的.step
为浏览器的每个动画帧调用函数,并允许更好的时间管理重绘,从而提高性能.
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 milliseconds 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);
}
})
}
Run Code Online (Sandbox Code Playgroud)
对于元素的Y位置,使用其他答案中的函数或下面提到的小提琴中的函数.
我设置了一个更复杂的功能,提供了支持和适当滚动到最底层的元素:https: //jsfiddle.net/s61x7c4e/
Ger*_*eri 25
刚刚在下面制作了这个javascript解决方案.
用法简单:
EPPZScrollTo.scrollVerticalToElementById('signup_form', 20);
Run Code Online (Sandbox Code Playgroud)
引擎对象(你可以使用filter,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);
}
};
Run Code Online (Sandbox Code Playgroud)
sur*_*gle 18
基于itnewb.com上的一篇文章,我做了一个演示插件,无需外部库就能顺利滚动.
javascript非常简单.首先是帮助函数,以改善跨浏览器支持以确定当前位置.
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;
}
Run Code Online (Sandbox Code Playgroud)
然后是一个函数来确定目标元素的位置 - 我们想要滚动到的位置.
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;
}
Run Code Online (Sandbox Code Playgroud)
而滚动的核心功能
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;
}
Run Code Online (Sandbox Code Playgroud)
要调用它,您只需执行以下操作即可.您可以使用id作为目标锚点的引用来创建指向另一个元素的链接.
<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>
Run Code Online (Sandbox Code Playgroud)
在itnewb.com的页脚中写道如下:The techniques, effects and code demonstrated in ITNewb articles may be used for any purpose without attribution (although we recommend it)
(2014-01-12)
Esn*_*Ezz 14
为什么不使用CSS的scroll-behavior属性
html {
scroll-behavior: smooth;
}
Run Code Online (Sandbox Code Playgroud)
浏览器支持也很好 https://caniuse.com/#feat=css-scroll-behavior
San*_*Shr 10
5年前提出的问题,我正在与我打交道,smooth scroll
觉得为需要的人提供简单的解决方案是值得的。所有答案都是好的,但是在这里您可以做一个简单的答案。
function smoothScroll () {
document.querySelector('.your_class or #id here').scrollIntoView({
behavior: 'smooth'
});
}
Run Code Online (Sandbox Code Playgroud)
只需在源smoothScroll
上调用onClick
event上的函数即可element
。
注意:请在此处检查兼容性
ani*_*the 10
您还可以查看这个很棒的博客 - 使用一些非常简单的方法来实现这一点:)
https://css-tricks.com/snippets/jquery/smooth-scrolling/
喜欢(来自博客)
// Scroll to specific values
// scrollTo is the same
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
// Scroll certain amounts from current position
window.scrollBy({
top: 100, // could be negative value
left: 0,
behavior: 'smooth'
});
// Scroll to a certain element
document.querySelector('.hello').scrollIntoView({
behavior: 'smooth'
});
Run Code Online (Sandbox Code Playgroud)
并且您还可以获得如下所示的元素“顶部”位置(或其他方式)
var e = document.getElementById(element);
var top = 0;
do {
top += e.offsetTop;
} while (e = e.offsetParent);
return top;
Run Code Online (Sandbox Code Playgroud)
有关平滑滚动方法的更全面列表,请参阅我的回答此处。
要在精确的时间内滚动到某个位置,window.requestAnimationFrame
可以使用每次计算适当的当前位置。要滚动到某个元素,只需将 y 位置设置为element.offsetTop
。
/*
@param pos: the y-position to scroll to (in pixels)
@param time: the exact amount of time the scrolling will take (in milliseconds)
*/
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
Run Code Online (Sandbox Code Playgroud)
演示:
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
document.getElementById("toElement").addEventListener("click", function(e){
scrollToSmoothly(document.querySelector('div').offsetTop, 500 /* milliseconds */);
});
document.getElementById("backToTop").addEventListener("click", function(e){
scrollToSmoothly(0, 500);
});
Run Code Online (Sandbox Code Playgroud)
<button id="toElement">Scroll To Element</button>
<div style="margin: 1000px 0px; text-align: center;">Div element
<button id="backToTop">Scroll back to top</button>
</div>
Run Code Online (Sandbox Code Playgroud)
还可以使用SmoothScroll.js库,它支持滚动到页面上的元素以及更复杂的功能,例如垂直和水平平滑滚动、在其他容器元素内滚动、不同的缓动行为、从当前位置相对滚动, 和更多。
document.getElementById("toElement").addEventListener("click", function(e){
smoothScroll({toElement: document.querySelector('div'), duration: 500});
});
document.getElementById("backToTop").addEventListener("click", function(e){
smoothScroll({yPos: 'start', duration: 500});
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdn.jsdelivr.net/gh/LieutenantPeacock/SmoothScroll@1.2.0/src/smoothscroll.min.js" integrity="sha384-UdJHYJK9eDBy7vML0TvJGlCpvrJhCuOPGTc7tHbA+jHEgCgjWpPbmMvmd/2bzdXU" crossorigin="anonymous"></script>
<button id="toElement">Scroll To Element</button>
<div style="margin: 1000px 0px; text-align: center;">Div element
<button id="backToTop">Scroll back to top</button>
</div>
Run Code Online (Sandbox Code Playgroud)
或者,您可以传递一个选项对象,window.scroll
该对象滚动到特定的 x 和 y 位置,并window.scrollBy
从当前位置滚动一定量:
// Scroll to specific values
// scrollTo is the same
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
// Scroll certain amounts from current position
window.scrollBy({
top: 100, // could be negative value
left: 0,
behavior: 'smooth'
});
Run Code Online (Sandbox Code Playgroud)
如果您只需要滚动到某个元素,而不是文档中的特定位置,则可以使用Element.scrollIntoView
with behavior
set to smooth
。
document.getElementById("elemID").scrollIntoView({
behavior: 'smooth'
});
Run Code Online (Sandbox Code Playgroud)
小智 5
我已经使用这个很长时间了:
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)
}
}
Run Code Online (Sandbox Code Playgroud)
用法:
scrollToItem(element)
其中,element
是document.getElementById('elementid')
例如。
归档时间: |
|
查看次数: |
71191 次 |
最近记录: |