我可以使用 css 或 jQuery 更改滚动速度吗?

发布于 2024-12-04 23:04:01 字数 1384 浏览 1 评论 0原文

在下面的示例中,我想降低 div 内容的滚动速度,尤其是在使用鼠标滚轮时,因为滚轮滚动大约是 div 的高度。

是否可以使用 CSS 来控制,如果不能,则使用 javascript(也许使用 jQuery)?

.scrollable {
    width: 500px;
    height: 70px;
    overflow: auto; 
}
<div class="scrollable">
    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
</div>

注意:我意识到操作系统/浏览器和浏览器设置之间的滚动速度可能有所不同。但我认为在大多数情况下,滚动速度(使用鼠标滚轮时)太快,所以我想放慢速度。

In the example below, I would like to reduce the scroll speed of the div's content, especially when using the mouse wheel, as one wheel tick scrolls approximately the div's height.

Is it possible to control that with CSS, and if not, javascript (perhaps using jQuery) ?

.scrollable {
    width: 500px;
    height: 70px;
    overflow: auto; 
}
<div class="scrollable">
    Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?
</div>

Note: I realize that the scroll speed might differ between os/browers and browser settings. But I think that in the majority of the cases, the scroll speed (when using the mouse wheel) is too fast, so I would like to slow it down.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

二智少女 2024-12-11 23:04:01

滚动速度可以通过 javascript(或 jQuery 等 js 库)进行更改、调整、反转。

你为什么要这样做?视差只是原因之一。我不知道为什么有人会反对这样做——同样的负面论点也可以反对隐藏 DIV、向上/向下滑动元素等。网站始终是技术功能和用户体验设计的结合——优秀的设计师可以使用几乎任何改善用户体验的技术能力。这就是他/她优秀的原因。

来自葡萄牙的 Toni Almeida 制作了精彩的演示,转载如下:

jsFiddle 演示

HTML:

<div id="myDiv">
    Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. <span class="boldit">Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. </span>
</div>

javascript/jQuery:

  function wheel(event) {
      var delta = 0;
      if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
      else if (event.detail) {(delta = -event.detail / 3);}

      handle(delta);
      if (event.preventDefault) {(event.preventDefault());}
      event.returnValue = false;
  }

  function handle(delta) {
      var time = 1000;
      var distance = 300;

      $('html, body').stop().animate({
          scrollTop: $(window).scrollTop() - (distance * delta)
      }, time );
  }

  if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
    window.onmousewheel = document.onmousewheel = wheel;

来源:

如何更改网页的默认滚动速度、滚动量、滚动惯性

The scroll speed CAN be changed, adjusted, reversed, all of the above - via javascript (or a js library such as jQuery).

WHY would you want to do this? Parallax is just one of the reasons. I have no idea why anyone would argue against doing so -- the same negative arguments can be made against hiding DIVs, sliding elements up/down, etc. Websites are always a combination of technical functionality and UX design -- a good designer can use almost any technical capability to improve UX. That is what makes him/her good.

Toni Almeida of Portugal created a brilliant demo, reproduced below:

jsFiddle Demo

HTML:

<div id="myDiv">
    Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. <span class="boldit">Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. </span>
</div>

javascript/jQuery:

  function wheel(event) {
      var delta = 0;
      if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
      else if (event.detail) {(delta = -event.detail / 3);}

      handle(delta);
      if (event.preventDefault) {(event.preventDefault());}
      event.returnValue = false;
  }

  function handle(delta) {
      var time = 1000;
      var distance = 300;

      $('html, body').stop().animate({
          scrollTop: $(window).scrollTop() - (distance * delta)
      }, time );
  }

  if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
    window.onmousewheel = document.onmousewheel = wheel;

Source:

How to change default scrollspeed,scrollamount,scrollinertia of a webpage

桃扇骨 2024-12-11 23:04:01

鼠标滚动甚至可以使用事件监听器在浏览器中使用 JS 进行覆盖。可以通过这种方式防止默认滚动行为,并实现您自己的行为(请参阅 cssyphus 的答案)。

然而,我认为这样做在可用性、可访问性和对用户的尊重方面是一个可怕的想法。

The mouse scroll even can be overwritten using JS within the browser using an event listener. It is possible to prevent default scrolling behavior this way, and implement your own behavior (see cssyphus's answer).

However, I think doing so is a HORRIBLE idea in terms of usability, accessibility, and respect for your users.

青巷忧颜 2024-12-11 23:04:01

我刚刚根据该代码制作了一个纯 Javascript 函数。
仅Javascript版本演示: http://jsbin.com/copidifiji

这是来自 jQuery 的独立代码

if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false); 
window.onmousewheel = document.onmousewheel = wheel;}

function wheel(event) {
    var delta = 0;
    if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
    else if (event.detail) delta = -(event.detail)/3;

    handle(delta);
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}

function handle(sentido) {
    var inicial = document.body.scrollTop;
    var time = 1000;
    var distance = 200;
  animate({
    delay: 0,
    duration: time,
    delta: function(p) {return p;},
    step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);   
    }});}

function animate(opts) {
  var start = new Date();
  var id = setInterval(function() {
    var timePassed = new Date() - start;
    var progress = (timePassed / opts.duration);
    if (progress > 1) {progress = 1;}
    var delta = opts.delta(progress);
    opts.step(delta);
    if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}

I just made a pure Javascript function based on that code.
Javascript only version demo: http://jsbin.com/copidifiji

That is the independent code from jQuery

if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false); 
window.onmousewheel = document.onmousewheel = wheel;}

function wheel(event) {
    var delta = 0;
    if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
    else if (event.detail) delta = -(event.detail)/3;

    handle(delta);
    if (event.preventDefault) event.preventDefault();
    event.returnValue = false;
}

function handle(sentido) {
    var inicial = document.body.scrollTop;
    var time = 1000;
    var distance = 200;
  animate({
    delay: 0,
    duration: time,
    delta: function(p) {return p;},
    step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);   
    }});}

function animate(opts) {
  var start = new Date();
  var id = setInterval(function() {
    var timePassed = new Date() - start;
    var progress = (timePassed / opts.duration);
    if (progress > 1) {progress = 1;}
    var delta = opts.delta(progress);
    opts.step(delta);
    if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}
尛丟丟 2024-12-11 23:04:01

一个简短而直接的香草 js 解决方案,用于增加/减少滚动速度/步长(deltaY):

    let custom_scroll = document.getElementById('custom-scroll');
    let scroll_timeout = undefined;
    let ratio = 0.25;//change this to increase/descrease scroll speed/step
    custom_scroll.addEventListener("wheel", (event) => {
        event.preventDefault();

        clearTimeout(scroll_timeout);//if the previous scroll didn't finish, need to stop it to prevent infinite scroll.

        let target = custom_scroll.scrollTop + event.deltaY * ratio;
        let step = target > custom_scroll.scrollTop ? 1 : -1;

        let frame = () => {
            custom_scroll.scrollTop += step;
            if((target < custom_scroll.scrollTop && step < 0) || (target > custom_scroll.scrollTop && step > 0)) {
              scroll_timeout = setTimeout(frame, 5);
            }
        }
        frame();
    });

//or even shorter version:
let custom_scroll_short = document.getElementById('custom-scroll-short');
custom_scroll_short.addEventListener("wheel", (event) => {
      event.preventDefault();

      let target = custom_scroll_short.scrollTop + event.deltaY * ratio;

      custom_scroll_short.scrollTo({
        top: target,
        behavior: "smooth"
      })
});
#custom-scroll, #custom-scroll-short {
      width: 200px;
      height: 100px;
      background-color: gray;
      overflow-y: scroll;
      margin: 50px;
    }
<div id="custom-scroll">
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
    </div>

    <div id="custom-scroll-short">
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
    </div>

A short and straightforward vanilla js solution to increase/decrease scrolling speed/step(deltaY):

    let custom_scroll = document.getElementById('custom-scroll');
    let scroll_timeout = undefined;
    let ratio = 0.25;//change this to increase/descrease scroll speed/step
    custom_scroll.addEventListener("wheel", (event) => {
        event.preventDefault();

        clearTimeout(scroll_timeout);//if the previous scroll didn't finish, need to stop it to prevent infinite scroll.

        let target = custom_scroll.scrollTop + event.deltaY * ratio;
        let step = target > custom_scroll.scrollTop ? 1 : -1;

        let frame = () => {
            custom_scroll.scrollTop += step;
            if((target < custom_scroll.scrollTop && step < 0) || (target > custom_scroll.scrollTop && step > 0)) {
              scroll_timeout = setTimeout(frame, 5);
            }
        }
        frame();
    });

//or even shorter version:
let custom_scroll_short = document.getElementById('custom-scroll-short');
custom_scroll_short.addEventListener("wheel", (event) => {
      event.preventDefault();

      let target = custom_scroll_short.scrollTop + event.deltaY * ratio;

      custom_scroll_short.scrollTo({
        top: target,
        behavior: "smooth"
      })
});
#custom-scroll, #custom-scroll-short {
      width: 200px;
      height: 100px;
      background-color: gray;
      overflow-y: scroll;
      margin: 50px;
    }
<div id="custom-scroll">
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
    </div>

    <div id="custom-scroll-short">
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
        <p>Item</p>
    </div>

深陷 2024-12-11 23:04:01

除了之前的答案之外,回答原始问题的这一部分也很重要:

“用 CSS 可以吗?

(自动)滚动行为可以设置为“平滑”,但速度为 该属性。

html { scroll-behavior: smooth; }

在这种情况下,saldy 答案是否定的:无法使用 CSS 设置或更改该属性

例如在 Firefox 中,您可以使用 general.smoothScroll about:config 浏览器选项卡中的选项和值,但请确保不要篡改可以在此处更改的其他重要设置。

In addition to previous answers it's also important to reply this part of the original question:

"Is it possible ... with CSS?

The (auto) scroll behavior can be set to 'smooth' but speed is set by the browser.

html { scroll-behavior: smooth; }

In this case, saldy the answer is no: the smooth scrolling speed cannot be set or changed using CSS. This property is handled by the browser.

In Firefox for example you can play with general.smoothScroll options and values in the about:config browser tab, but be sure not to tamper other important settings that can be changed there.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文