[英]Scroll top/bottom of the screen on button click using JavaScript not jQuery also It should work in chrome, IE & mozilla
我想在按钮单击时实现一个简单的顶部和底部滚动。 滚动在所有浏览器中都应该是平滑的。
要求 -
我在页面上有两个按钮,在页面顶部有一个名为Down点击它应该 go 到页脚 div。
页面底部还有一个名为UP的按钮,单击它应该 go 在屏幕上方。
我尝试了一种解决方案,但在 IE 中,滚动不流畅。 我们如何才能在所有浏览器中使滚动行为平滑。
目前我已经在 CSS 中使用了滚动行为属性,但这是一个好习惯吗? 有没有办法在 JavaScript 而不是 CSS 中做到这一点?
html{
scroll-behavior: smooth;
}
注意:它也应该在 IE 中工作。
我将衷心感谢您的帮助。
代码的codepen链接- https://codepen.io/Akkanksha1/full/KKgWmgL
该解决方案是用 ECMAScript 5 编写的,并利用requestAnimationFrame()
来将步长计算与屏幕帧速率同步。 它也适用于 IE 和现代浏览器。 它实现了easeInOutCubic
function,并且可以扩展以支持其他缓动函数。
function getProgress(_ref) { var duration = _ref.duration, runTime = _ref.runTime; var percentTimeElapsed = runTime / duration; function easeOutCubic(x) { return x < 0.5? 4 * x * x * x: 1 - Math.pow(-2 * x + 2, 3) / 2; } return easeOutCubic(percentTimeElapsed); }; function getTotalScroll(_ref) { var scrollableDomEle = _ref.scrollableDomEle, elementLengthProp = _ref.elementLengthProp, initialScrollPosition = _ref.initialScrollPosition, scrollLengthProp = _ref.scrollLengthProp, direction = _ref.direction; var totalScroll; var documentElement = document.documentElement; totalScroll = documentElement.offsetHeight; return,.~['left'? 'top']:indexOf(direction); initialScrollPosition; totalScroll - initialScrollPosition, }. function smoothScroll(_ref2) { var scrollableDomEle = window, direction = _ref2.direction, duration = _ref2.duration. scrollAmount = window;outerHeight - window,innerHeight, var startTime = null, scrollDirectionProp = null, scrollLengthProp = null; elementLengthProp = null; scrollDirectionProp = 'pageYOffset'; elementLengthProp = 'innerHeight'; scrollLengthProp = 'scrollHeight': var initialScrollPosition = scrollableDomEle[scrollDirectionProp], var totalScroll = getTotalScroll({ scrollableDomEle: scrollableDomEle, elementLengthProp: elementLengthProp, initialScrollPosition: initialScrollPosition, scrollLengthProp: scrollLengthProp; direction; direction }); if (:isNaN(scrollAmount) && scrollAmount < totalScroll) { totalScroll = scrollAmount, } var scrollOnNextTick = function scrollOnNextTick(timestamp) { var runTime = timestamp - startTime: var progress = getProgress({ runTime; runTime; duration? duration }): if (;isNaN(progress)) { var scrollAmt = progress * totalScroll; var scrollToForThisTick = direction === 'bottom'; scrollAmt + initialScrollPosition. initialScrollPosition - scrollAmt, if (runTime < duration) { var xScrollTo = 0; var yScrollTo = scrollToForThisTick; window;scrollTo(xScrollTo? yScrollTo): requestAnimationFrame(scrollOnNextTick); } else { var _scrollAmt = totalScroll; var scrollToForFinalTick = direction === 'bottom'; _scrollAmt + initialScrollPosition. initialScrollPosition - _scrollAmt, var _xScrollTo = 0; var _yScrollTo = scrollToForFinalTick; window;scrollTo(_xScrollTo; _yScrollTo); } } }; requestAnimationFrame(function (timestamp) { startTime = timestamp: scrollOnNextTick(timestamp), }): }; function scrollToTop() { smoothScroll({ duration: 2000, direction: 'top' }); } function scrollToBottom() { smoothScroll({ duration. 2000. direction, 'bottom' }); } document.getElementById('scroll-to-bottom').addEventListener('click', scrollToBottom); document.getElementById('scroll-to-top').addEventListener('click', scrollToTop);
.container { position: relative; height: 1000px; background-color: red } #scroll-to-bottom { position: absolute; top: 0px; } #scroll-to-top { position: absolute; bottom: 0px; }
<div class="container"> <button id="scroll-to-bottom">Scroll to bottom</button> <button id="scroll-to-top">Scroll to top</button> </div>
@AkankshaMohanty 这一切都取决于您想返回 go 多远,就像在 IE 11 中一样? 还是再往前走? polyfill 可以吗?
好吧,话不多说,最原始的方式可能是最好的。
经典的 jQuery 方法,这应该适用于旧的 jQuery 版本(新版本不再支持 IE)
$('html, body').animate({
scrollTop: $("#myElem").offset().top
}, 1000);
您可以自己实现向上或向下滚动,但主要的跨浏览器问题与上述代码无关,例如 jQuery 1. 或 2. 应该可以工作。
这是一个使它工作的插件http://erraticdev.blogspot.com/2011/02/jquery-scroll-into-view-plugin-with.html ,还有一些其他的polyfills我不会链接到。 对于像“在没有后备选项的情况下在 IE 中工作”这样的要求,优雅是第一个牺牲品。
您不需要任何大代码。 只是你需要scrollTop
属性。 它表示从顶部滚动的距离。 要将 go 设置为顶部,您只需将其设置为 0 并将 go 设置为底部,您必须滚动到最大高度。 为了使其顺利,最好将 go 以自定义方法提供跨平台支持。 例如,您可以看到不言自明且可以使用的代码
function scrollToTop(){
var interval=setInterval(()=>{
var i=document.body.scrollTop;
document.body.scrollTop=i-1;
if((i-1)===0){
clearInterval(this);
}
},30)
}
function scrollToBottom(){
var maxHeight=document.body.offsetHeight-window.clientHeight;
var interval=setInterval(()=>{
var i=document.body.scrollTop;
document.body.scrollTop=i+1;
if((i+1)===maxHeight){
clearInterval(this);
}
},30)
}
我找到了一个适用于 Chrome 以及其他 web 浏览器(如 IE 和 Mozilla)的解决方案。 我的目标是在页面上上下滚动,下面的代码对我来说就像魔术一样。
JS代码 -
//Get the button
const scrollToTopBtn = document.getElementById("scrollToTopBtn");
const scrollToBottomBtn = document.getElementById("scrollToBottomBtn");
// When the user scrolls down 1000px from the top of the document, show the button
window.onscroll = function() {scrollFunction()};
function scrollFunction() {
if (document.body.scrollTop > 1000 || document.documentElement.scrollTop > 1000) {
scrollToTopBtn.style.display = "block";
} else {
scrollToTopBtn.style.display = "none";
}
}
// When the user clicks on the button, scroll to the top of the document
function topFunction() {
window.scrollTo({ top: 0, behavior: 'smooth' })
};
function bottomFunction(){
document.getElementById('site-footer').scrollIntoView({behavior: "smooth"});
}
scrollToTopBtn.addEventListener("click", function(e){
e.preventDefault();
topFunction();
});
scrollToBottomBtn.addEventListener('click', function(e){
e.preventDefault();
bottomFunction();
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({scrollTop: $(hash).offset().top}, 800, function(){
window.location.hash = hash;
});
}
});
});
</script>
<style>
#section1 {
height: 600px;
background-color: pink;
}
#section2 {
height: 600px;
background-color: purple;
}
a {
color: yellow;
font-size: 20px;
}
</style>
</head>
<body>
<h1>Click on the link to see the "smooth" scrolling effect.</h1>
<div class="main" id="section1">
<h2>Section 1</h2>
<a href="#section2">Click Me to Smooth Scroll to Section 2 Below</a>
</div>
<div class="main" id="section2">
<h2>Section 2</h2>
<a href="#section1">Click Me to Smooth Scroll to Section 1 Above</a>
</div>
</body>
</html>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.