javascript 平滑滚动到顶部
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15935318/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
smooth scroll to top
提问by user2267388
I've bean searching for this for a few hours now and I have no solution. I want a smooth scroll to the top of the page. I already have smooth scrolling to separate anchors in the page with a .js
file attatched to my site but I cannot use an anchor for the top, because I'm using a template from a free hosting site with built in page building tools that do not allow me to edit above the body area.
我已经搜索了几个小时,但没有解决方案。我想要平滑滚动到页面顶部。我已经平滑滚动到页面中的单独锚点,.js
文件附加到我的网站,但我不能在顶部使用锚点,因为我使用的是来自免费托管网站的模板,内置页面构建工具不允许我在身体区域上方进行编辑。
Here's where I got the smooth scrolling. I've been trying to set up "smoothly-scroll-to-an-element-without-a-jquery-plugin" but I have no idea how to arrange it obviously after countless attempts. I've also used window.scrollTo(0, 0);
but it scrolls instantly. Thanks!
这是我获得平滑滚动的地方。我一直在尝试设置“smoothly-scroll-to-an-element-without-a-jquery-plugin”,但经过无数次尝试后,我不知道如何明显地安排它。我也用过,window.scrollTo(0, 0);
但它会立即滚动。谢谢!
In addition:
http://jsfiddle.net/WFd3V/- the code would probably be the tag class="smoothScroll"
since my other element uses that, but I don't know how to mix it with the href="javascript:window.scrollTo(0,0);"
, or anything else that would bring the page to the top without an anchor.
另外:
http://jsfiddle.net/WFd3V/-代码很可能是标签class="smoothScroll"
,因为我的其他元素的使用,但我不知道如何将它与混合href="javascript:window.scrollTo(0,0);"
,或其他任何将带给页面没有锚的顶部。
回答by Gor
Here is my proposal implemented with ES6
这是我用 ES6 实现的建议
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
scrollToTop();
Tip:for slower motion of the scrolling, increase the hardcoded number 8
. The bigger the number - the smoother/slower the scrolling.
提示:对于较慢的滚动动作,请增加硬编码数字8
。数字越大 - 滚动越平滑/越慢。
回答by theMaxx
I think the simplest solution is:
我认为最简单的解决方案是:
window.scrollTo({top: 0, behavior: 'smooth'});
If you wanted instant scrolling then just use:
如果您想要即时滚动,则只需使用:
window.scrollTo({top: 0});
Can be used as a function:
可以用作函数:
// Scroll To Top
function scrollToTop() {
window.scrollTo({top: 0, behavior: 'smooth'});
}
Or as an onclick handler:
或者作为一个 onclick 处理程序:
<button onclick='window.scrollTo({top: 0, behavior: "smooth"});'>Scroll to Top</button>
回答by Nikhil sHETH
Pure Javascript only
仅纯 Javascript
var t1 = 0;
window.onscroll = scroll1;
function scroll1() {
var toTop = document.getElementById('toTop');
window.scrollY > 0 ? toTop.style.display = 'Block' : toTop.style.display = 'none';
}
function abcd() {
var y1 = window.scrollY;
y1 = y1 - 1000;
window.scrollTo(0, y1);
if (y1 > 0) {
t1 = setTimeout("abcd()", 100);
} else {
clearTimeout(t1);
}
}
#toTop {
display: block;
position: fixed;
bottom: 20px;
right: 20px;
font-size: 48px;
}
#toTop {
transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;
opacity: 0.5;
display: none;
cursor: pointer;
}
#toTop:hover {
opacity: 1;
}
<p>your text here</p>
<img id="toTop" src="http://via.placeholder.com/50x50" onclick="abcd()" title="Go To Top">
回答by Nikhil sHETH
You should start using jQuery or some other js lib. It's way easier than js, and you can use it as a shorthand for most js instead of actually long, drawn out js.
您应该开始使用 jQuery 或其他一些 js 库。它比 js 容易得多,你可以将它用作大多数 js 的简写,而不是实际上很长的、绘制出来的 js。
Simply put <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
(or whatever the latest google cdn is https://developers.google.com/speed/libraries/devguide#jquery) in your <head>
.
简单地将<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
(或任何最新的谷歌 CDN 是https://developers.google.com/speed/libraries/devguide#jquery)放在您的<head>
.
Then, inside your event
code (much easier if you use jQuery: $.click()
for buttons, $.change()
for checkboxes, selects, radios...), put the code from your second link looking more like
然后,在您的event
代码中(如果您使用 jQuery 会更容易:$.click()
对于按钮、$.change()
复选框、选择、单选...),将第二个链接中的代码看起来更像
$('#theIDofTheButtonThatTriggersThisAnimation').click(function(){
$('#theIDofTheElementYouWantToSmoothlyScroll').animate({
scrollTop: 0
}, 2000);
});
However, if you're trying to do animations, I recommend you look into some basic css properties like position:absolute
and position:relative
to keep from going crazy.
但是,如果您正在尝试制作动画,我建议您查看一些基本的 css 属性,例如position:absolute
并position:relative
避免发疯。
I'm still not quite sure what's going on in your code because it's very non-standard relative to how things are done now with css & jQuery. I'd break it down into something simple to learn the general concept.
我仍然不太确定您的代码中发生了什么,因为相对于现在使用 css 和 jQuery 的处理方式而言,它非常不标准。我会把它分解成一些简单的东西来学习一般概念。
For your example, you should build off of my animation example, how I learned: https://stackoverflow.com/a/12906254/1382306
对于您的示例,您应该基于我的动画示例,我是如何学习的:https: //stackoverflow.com/a/12906254/1382306
I think you're trying to move your text up and down based upon a $.click()
. In the fiddle in my answer, it slides left and right. You can easily reformat up and down by using the css top
property instead of left
.
我认为您正在尝试根据$.click()
. 在我的答案中的小提琴中,它向左和向右滑动。您可以使用 csstop
属性而不是left
.
Once you figure out how to move the entire div
up and down, you can make a relative
container to hold all of the content absolute
div
s and manipulate all content div
s with a loop by setting their top
s. Here's a quick primer on absolute
in relative
: http://css-tricks.com/absolute-positioning-inside-relative-positioning/
一旦你弄清楚如何上下移动整个div
,你就可以制作一个relative
容器来容纳所有的内容absolute
div
s 并div
通过设置它们的top
s 来循环操作所有内容s。这里有一个快速入门absolute
中relative
:http://css-tricks.com/absolute-positioning-inside-relative-positioning/
All of my animations have relative
containers and absolute
content. It's how I made a custom gridview plugin that can instantly zip through an entire database.
我所有的动画都有relative
容器和absolute
内容。这就是我制作自定义 gridview 插件的方式,该插件可以立即压缩整个数据库。
Also, there really is no overuse of div
s when it comes to animating. Trying to make 1 div
do everything is a nightmare.
此外,在div
动画方面确实没有过度使用s 。试图让 1div
做所有事情是一场噩梦。
Try to see if you can reformat my fiddle into a vertical slide out. Once you've done that, research absolute
in relative
a little. If you have any more problems, just ask another question.
试试看你能不能把我的小提琴重新格式化成垂直滑出。一旦你做到这一点,研究absolute
在relative
一点点。如果您有更多问题,请再问一个问题。
Change your thinking to these philosophies, and you'll start flying through this type of coding.
将您的想法转变为这些哲学,您将开始快速浏览此类编码。
回答by BitDEVil2K16
Hmm coment funtion off for me,
嗯,为我关闭评论功能,
try this
试试这个
$(document).ready(function(){
$("#top").hide();
$(function toTop() {
$(window).scroll(function () {
if ($(this).scrollTop() > 100) {
$('#top').fadeIn();
} else {
$('#top').fadeOut();
}
});
$('#top').click(function () {
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
});
});
#top {
float:right;
width:39px;
margin-top:-35px;
}
#top {
transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;
opacity: 0.5;
display:none;
cursor: pointer;
}
#top:hover {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
<div id="top" onclick="toTop()"><img src="to_top.png" alt="no pic "/> klick to top</div>
回答by Akimbas
Some time has passed since this was asked.
自从提出这个问题以来已经过去了一段时间。
Now it is possible to not only specify number to window.scroll function, but also pass an object with three properties: top, left and behavior. So if we would like to have a smooth scroll up with native JavaScript, we can now do something like this:
现在不仅可以为 window.scroll 函数指定数字,还可以传递具有三个属性的对象:顶部、左侧和行为。因此,如果我们想使用原生 JavaScript 平滑向上滚动,我们现在可以执行以下操作:
let button = document.querySelector('button-id');
let options = {top: 0, left: 0, behavior: 'smooth'}; // left and top are coordinates
button.addEventListener('click', () => { window.scroll(options) });
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
https://developer.mozilla.org/en-US/docs/Web/API/Window/scroll
回答by Waruna Manjula
You can simply use
你可以简单地使用
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
document.getElementById("gotoTop").style.display = "block";
} else {
document.getElementById("gotoTop").style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
$('html, body').animate({scrollTop:0}, 'slow');
}
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 20px;
}
#gotoTop {
display: none;
position: fixed;
bottom: 20px;
right: 30px;
z-index: 99;
font-size: 18px;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 15px;
border-radius: 4px;
}
#gotoTop:hover {
background-color: #555;
}
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<button onclick="topFunction()" id="gotoTop" title="Go to top">Top</button>
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
回答by Ron16
Elegant easy solution using jQuery.
使用 jQuery 的优雅简单的解决方案。
<script>
function call() {
var body = $("html, body");
body.stop().animate({scrollTop:0}, 500, 'swing', function() {
});
}
</script>
and in your html :
<div onclick="call()"><img src="../img/[email protected]"></div>
并在您的 html 中:
<div onclick="call()"><img src="../img/[email protected]"></div>
回答by vichu
I just customized BootPc Deutschland's answer
我只是定制了 BootPc Deutschland 的答案
You can simply use
你可以简单地使用
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('body,html').animate({
scrollTop: 0
}, 800);
$('#btn-go-to-top').click(function () {
$('body,html').animate({
scrollTop: 0
}, 800);
return false;
});
});
</script>
this will help you to smoothly scroll to the top of the page.
这将帮助您顺利滚动到页面顶部。
and for styling
和造型
#btn-go-to-top {
opacity: .5;
width:4%;
height:8%;
display: none;
position: fixed;
bottom: 5%;
right: 3%;
z-index: 99;
border: none;
outline: none;
background-color: red;
color: white;
cursor: pointer;
padding: 10px;
border-radius: 50%;
}
#btn-go-to-top:hover {
opacity: 1;
}
.top {
transition: all 0.5s ease 0s;
-moz-transition: all 0.5s ease 0s;
-webkit-transition: all 0.5s ease 0s;
-o-transition: all 0.5s ease 0s;
}
this styling makes the button arrive at the bottom-right of the page.
这种样式使按钮到达页面的右下角。
and in your page you can add the button to go to top like this
在您的页面中,您可以添加按钮以像这样转到顶部
<div id="btn-go-to-top" class="text-center top">
<img src="uploads/Arrow.png" style="margin: 7px;" width="50%" height="50%">
</div>
hope this help you.if you have any doubts you are always free to ask me
希望这对你有帮助。如果你有任何疑问,你可以随时问我
回答by Kapil soni
also used below:
下面也使用:
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;