![]() |
坏坏的眼镜 · 【Unity】2D ...· 1 月前 · |
![]() |
奔放的包子 · Unity中父物体CanvasGroup组件 ...· 1 月前 · |
![]() |
痴情的墨镜 · 2024武汉网球公开赛开票啦!票价表_腾讯新闻· 3 月前 · |
![]() |
失望的铁链 · VUE格式探究记录_intergraph ...· 6 月前 · |
![]() |
小胡子的薯片 · 国民老公带回家:偷吻55次漫画|官方在线漫画 ...· 1 年前 · |
![]() |
八块腹肌的烈酒 · 就算是在唐家三少笔下全部主角中,唐三也是最强的一个· 1 年前 · |
![]() |
追风的便当 · 中国企业荣膺北威州投资奖· 1 年前 · |
我想在不使用jQuery的情况下平滑地滚动到一个元素--只使用纯javascript。我希望一个通用的功能,能够顺利地向下滚动和向上滚动到文档中的特定位置。
我知道我可以在jQuery中使用以下内容:
$('html, body').animate({
scrollTop: $('#myelementid').offset().top
}, 500);
如果只用javascript我该怎么做呢?
这就是我想要做的:
function scrollToHalf(){
//what do I do?
function scrollToSection(){
//What should I do here?
}
<input type="button" onClick="scrollToHalf()" value="Scroll To 50% of Page">
<input type="button" onClick="scrollToSection()" value="Scroll To Section1">
<section style="margin-top: 1000px;" id="section1">
This is a section
</section>
在jquery中,我会这样做:
html, body{
height: 3000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" onClick="scrollToHalf()" value="Scroll To 50% of Page">
<input type="button" onClick="scrollToSection()" value="Scroll To Section1">
<section style="margin-top: 1000px;" id="section1">
This is a section
</section>
<script>
function scrollToHalf(){
var height = $('body').height();
$('html, body').animate({
scrollTop: height/2
}, 500);
function scrollToSection(){
$('html, body').animate({
scrollTop: $('#section1').offset().top
}, 500);
</script>
编辑:我也希望能够平滑滚动到页面上的某个位置
编辑: CSS解决方案也是受欢迎的(尽管我更喜欢javascript解决方案)
要在一段精确的时间内滚动到某个位置,可以使用
window.requestAnimationFrame
,每次计算相应的当前位置。当不支持
requestAnimationFrame
时,可以使用
setTimeout
来达到类似的效果。
/*
@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);
}
演示:
/*
@param time: the exact amount of time the scrolling will take (in milliseconds)
@param pos: the y-position to scroll to (in pixels)
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);
}
<button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 300)">
Scroll To Div (300ms)
</button>
<button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 200)">
Scroll To Div (200ms)
</button>
<button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 100)">
Scroll To Div (100ms)
</button>
<button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 50)">
Scroll To Div (50ms)
</button>
<button onClick="scrollToSmoothly(document.querySelector('div').offsetTop, 1000)">
Scroll To Div (1000ms)
</button>
<div style="margin: 500px 0px;">
DIV<p/>
<button onClick="scrollToSmoothly(0, 500)">
Back To Top
</button>
<button onClick="scrollToSmoothly(document.body.scrollHeight)">
Scroll To Bottom
</button>
<div style="margin: 500px 0px;">
<button style="margin-top: 100px;" onClick="scrollToSmoothly(500, 3000)">
Scroll To y-position 500px (3000ms)
</button>
对于更复杂的情况,可以使用 SmoothScroll.js library ,它可以处理垂直和水平平滑滚动、在其他容器元素内滚动、不同的缓动行为、从当前位置相对滚动等。
var easings = document.getElementById("easings");
for(var key in smoothScroll.easing){
if(smoothScroll.easing.hasOwnProperty(key)){
var option = document.createElement('option');
option.text = option.value = key;
easings.add(option);
document.getElementById('to-bottom').addEventListener('click', function(e){
smoothScroll({yPos: 'end', easing: easings.value, duration: 2000});
document.getElementById('to-top').addEventListener('click', function(e){
smoothScroll({yPos: 'start', easing: easings.value, duration: 2000});
});
<script src="https://cdn.jsdelivr.net/gh/LieutenantPeacock/SmoothScroll@1.2.0/src/smoothscroll.min.js" integrity="sha384-UdJHYJK9eDBy7vML0TvJGlCpvrJhCuOPGTc7tHbA+jHEgCgjWpPbmMvmd/2bzdXU" crossorigin="anonymous"></script>
<!-- Taken from one of the library examples -->
Easing: <select id="easings"></select>
<button id="to-bottom">Scroll To Bottom</button>
<button id="to-top" style="margin-top: 5000px;">Scroll To Top</button>
或者,可以将options对象传递给
window.scroll
和
window.scrollBy
,前者滚动到特定的x和y位置,后者从当前位置滚动一定数量:
// 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'
});
演示:
<button onClick="scrollToDiv()">Scroll To Element</button>
<div style="margin: 500px 0px;">Div</div>
<script>
function scrollToDiv(){
var elem = document.querySelector("div");
window.scroll({
top: elem.offsetTop,
left: 0,
behavior: 'smooth'
</script>
如果只需要滚动到某个元素,而不需要滚动到文档中的特定位置,则可以使用
Element.scrollIntoView
,并将
behavior
设置为
smooth
。
document.getElementById("elemID").scrollIntoView({
behavior: 'smooth'
});
演示:
<button onClick="scrollToDiv()">Scroll To Element</button>
<div id="myDiv" style="margin: 500px 0px;">Div</div>
<script>
function scrollToDiv(){
document.getElementById("myDiv").scrollIntoView({
behavior: 'smooth'
</script>
现代浏览器支持
scroll-behavior
CSS property
,它可用于使文档中的滚动变得平滑(不需要JavaScript)。锚标签可以通过给锚标签一个
#
的
href
加上要滚动到的元素的
id
)来实现这一点。您还可以为特定容器(如
div
)设置
scroll-behavior
属性,以使其内容平滑滚动。
演示:
html, body{
scroll-behavior: smooth;
a, a:visited{
color: initial;
}
<a href="#elem">Scroll To Element</a>
<div id="elem" style="margin: 500px 0px;">Div</div>
在使用JavaScript时,CSS
scroll-behavior
属性也适用于
window.scrollTo
。
演示:
html, body{
scroll-behavior: smooth;
}
<button onClick="scrollToDiv()">Scroll To Element</button>
<div style="margin: 500px 0px;">Div</div>
<script>
function scrollToDiv(){
var elem = document.querySelector("div");
window.scrollTo(0, elem.offsetTop);
</script>
若要检查是否支持
scroll-behavior
属性,可以检查它是否作为HTML元素的样式中的键存在。
var scrollBehaviorSupported = 'scroll-behavior' in document.documentElement.style;
console.log('scroll-behavior supported:', scrollBehaviorSupported);
考虑使用
Element.scrollIntoView()
。
正如我在评论中提到的,当您试图滚动到指定的元素时,
scrollIntoView
是一个很好的选择--它会得到越来越多的浏览器支持--比如您显然想要对
scrollToSection
函数做什么。
要滚动到页面中间,可以将
body
和/或
html
元素的
scrollTop
属性设置为body的
scrollHeight
和窗口的
innerHeight
之差的一半。把上面的计算和
requestAnimationFrame
结合起来,你就完成了。
下面是如何将上述建议合并到您的代码中:
function scrollToHalf(duration) {
heightDiff = document.body.scrollHeight - window.innerHeight,
endValue = heightDiff / 2,
start = null;
/* Set a default for the duration, in case it's not given. */
duration = duration || 300;
/* Start the animation. */
window.requestAnimationFrame(function step (now) {
/* Normalise the start date and calculate the current progress. */
start = !start ? now : start;
var progress = now - start;
/* Increment by a calculate step the value of the scroll top. */
document.documentElement.scrollTop = endValue * progress / duration;
document.body.scrollTop = endValue * progress / duration;
/* Check whether the current progress is less than the given duration. */
if (progress < duration) {
/* Execute the function recursively. */
window.requestAnimationFrame(step);
else {
/* Set the scroll top to the end value. */
document.documentElement.scrollTop = endValue;
document.body.scrollTop = endValue;
function scrollToSection(element) {
/* Scroll until the button's next sibling comes into view. */
element.nextElementSibling.scrollIntoView({block: "start", behavior: "smooth"});
}
#section1 {
margin: 1000px 0;
border: 1px solid red
}
<input type="button" onClick="scrollToHalf()" value="Scroll To 50% of Page">
<input type="button" onClick="scrollToSection(this)" value="Scroll To Section1">
<section id="section1">
![]() |
痴情的墨镜 · 2024武汉网球公开赛开票啦!票价表_腾讯新闻 3 月前 |
![]() |
八块腹肌的烈酒 · 就算是在唐家三少笔下全部主角中,唐三也是最强的一个 1 年前 |
![]() |
追风的便当 · 中国企业荣膺北威州投资奖 1 年前 |