Is there a way to make horizontal scrolling smoother

后端 未结 6 2073
长情又很酷
长情又很酷 2021-02-05 17:52

This fiddle is almost what I\'m looking for, I got it from MDN. The only thing missing is that I want to make it smoother. Is there a way to do that without using jQuery or any

相关标签:
6条回答
  • 2021-02-05 18:14

    If you don't want to keep track of the scroll position, you can use scrollBy instead of scrollTo.

      container.scrollBy({
        top: 0,
        left: +500,
        behavior: 'smooth'
      }) 
    
    0 讨论(0)
  • 2021-02-05 18:24

    Adding scroll-behavior: smooth; to #container will make it smooth.

    Here is example on this Fiddle

    0 讨论(0)
  • 2021-02-05 18:27

    You can also use the .scrollTo method. I've modified the jsFidlle with this javascript :

    https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTo

    var container = document.getElementById('container');
    var input = document.getElementById('content');
    var scrollAmount = 0;
    var scrollMin = 0
    var scrollMax = input.clientWidth
    
    document.getElementById('slide').onclick = function () {
      container.scrollTo({
        top: 0,
        left: Math.max(scrollAmount += 500, scrollMax),
        behavior: 'smooth'
      });
    };
    
    
    document.getElementById('slideBack').onclick = function () {
      container.scrollTo({
        top: 0,
        left: Math.min(scrollAmount -= 500, scrollMin),
        behavior: 'smooth'
      });
    };
    
    0 讨论(0)
  • 2021-02-05 18:27

    you can do it vertically with jquery although i'm sure it can be adjusted to be done horizontally. The demo is here

    There's a javascript smoothscroll on github too added by cfernandi

    Also ccheck out iscroll.js

    $(function() {
      $('a[href*=#]:not([href=#])').click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
          var target = $(this.hash);
          target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
          if (target.length) {
            $('html,body').animate({
              scrollTop: target.offset().top
            }, 1000);
            return false;
          }
        }
      });
    });
    
    0 讨论(0)
  • 2021-02-05 18:33

    This could probably be optimised a fair bit, but here is a basic example of how you could do it using setInterval and clearInterval

    Fiddle

    Update

    Here is another example of it wrapped into a function instead, bit easier to tweak the speed etc.

    Fiddle

    0 讨论(0)
  • 2021-02-05 18:37

    Add scroll-behavior: smooth; to the scroll element. I feel it better

    0 讨论(0)
提交回复
热议问题