简体   繁体   English

使用 JavaScript 而不是 jQuery 按钮单击时滚动屏幕的顶部/底部 它应该在 chrome、IE 和 mozilla 中工作

[英]Scroll top/bottom of the screen on button click using JavaScript not jQuery also It should work in chrome, IE & mozilla

I wanted to implement a simple top and bottom scroll on button click.我想在按钮单击时实现一个简单的顶部和底部滚动。 the scroll should be smooth in all browsers.滚动在所有浏览器中都应该是平滑的。

Requirements -要求 -

I have two buttons on the page, on top of the page there is a button called Down on clicking on that It should go down to the footer div.我在页面上有两个按钮,在页面顶部有一个名为Down点击它应该 go 到页脚 div。

There is one more button on the bottom of the page called UP on clicking on that It should go up of the screen.页面底部还有一个名为UP的按钮,单击它应该 go 在屏幕上方。

I have tried one solution but in IE, the scroll is not smooth.我尝试了一种解决方案,但在 IE 中,滚动不流畅。 How can we make the scroll behavior smooth in all browsers.我们如何才能在所有浏览器中使滚动行为平滑。

Currently I have used the scroll-behavior property in CSS but is it a good practice?目前我已经在 CSS 中使用了滚动行为属性,但这是一个好习惯吗? Is there any way to do it in JavaScript instead of CSS?有没有办法在 JavaScript 而不是 CSS 中做到这一点?

html{
  scroll-behavior: smooth;
}

NOTE: It should also work in IE.注意:它也应该在 IE 中工作。

I would really appreciate your help.我将衷心感谢您的帮助。

Link of codepen for code- https://codepen.io/Akkanksha1/full/KKgWmgL代码的codepen链接- https://codepen.io/Akkanksha1/full/KKgWmgL

This solution is written in ECMAScript 5 and makes use of requestAnimationFrame() in order to synchronize the step calculations with the screen framerate.该解决方案是用 ECMAScript 5 编写的,并利用requestAnimationFrame()来将步长计算与屏幕帧速率同步。 It works in IE and in modern browsers as well.它也适用于 IE 和现代浏览器。 It implements the easeInOutCubic function, and could be extended to support other easing functions.它实现了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 this all depends on how far you would like to go back, as in IE 11? @AkankshaMohanty 这一切都取决于您想返回 go 多远,就像在 IE 11 中一样? Or further back?还是再往前走? Are polyfills ok? polyfill 可以吗?

Well anyway, without further ado, the most primitive way can be the best.好吧,话不多说,最原始的方式可能是最好的。

Classic jQuery approach, this should work with older jQuery versions(the new version do not support IE anymore)经典的 jQuery 方法,这应该适用于旧的 jQuery 版本(新版本不再支持 IE)

$('html, body').animate({
scrollTop: $("#myElem").offset().top
}, 1000);  

The scroll up or down you may implement yourself, but the main cross browser issue is a non issue with the above code, something like jQuery 1. or 2. should work.您可以自己实现向上或向下滚动,但主要的跨浏览器问题与上述代码无关,例如 jQuery 1. 或 2. 应该可以工作。

here is a plugin to make it work http://erraticdev.blogspot.com/2011/02/jquery-scroll-into-view-plugin-with.html , there are some other polyfills which I am not going to link to.这是一个使它工作的插件http://erraticdev.blogspot.com/2011/02/jquery-scroll-into-view-plugin-with.html ,还有一些其他的polyfills我不会链接到。 With requirements like "work in IE without a fallback option", elegance is the first victim.对于像“在没有后备选项的情况下在 IE 中工作”这样的要求,优雅是第一个牺牲品。

You dont need any large code.您不需要任何大代码。 Just you need scrollTop property.只是你需要scrollTop属性。 It indicates the distance scrolled from top.它表示从顶部滚动的距离。 To go to top you just have to set it to 0 and to go to bottom you have to scroll to maximum height.要将 go 设置为顶部,您只需将其设置为 0 并将 go 设置为底部,您必须滚动到最大高度。 To make it smooth it is better to go to custom approach to provide cross platform support.为了使其顺利,最好将 go 以自定义方法提供跨平台支持。 For example you can see the code which is self explanatory and ready to use例如,您可以看到不言自明且可以使用的代码

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

I have found a solution that works in Chrome and also in other web browsers like IE and Mozilla.我找到了一个适用于 Chrome 以及其他 web 浏览器(如 IE 和 Mozilla)的解决方案。 My goal was to have a up & down scroll on the page and the below code works like a magic for me.我的目标是在页面上上下滚动,下面的代码对我来说就像魔术一样。

JS Code - 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();
}); 

Working demo - https://codepen.io/Akkanksha1/full/KKgWmgL工作演示 - https://codepen.io/Akkanksha1/full/KKgWmgL

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM