有没有办法使用 JavaScript 控制滚动条?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8647806/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 04:06:11  来源:igfitidea点击:

Is there any way to control scroll bar using JavaScript?

javascriptscrollbarbrowser-scrollbars

提问by Mad coder.

In my below code a function to scroll DIV for every set of intervals where when I try to scroll up due to interval refresh scroll bar again coming down.

在我下面的代码中,一个函数可以为每组间隔滚动 DIV,当我尝试向上滚动时,由于间隔刷新滚动条再次下降。

My code:

我的代码:

   var int = self.setInterval("f2()", 1000);
   function f2() {
   var objDiv = document.getElementById("messages2");
   objDiv.scrollTop = objDiv.scrollHeight;
   }

Now, by using onscrollproperty for DIV is there anyway to stop scrolling down when holding scroll bar with mouse?

现在,通过onscroll对 DIV使用属性,是否可以在用鼠标按住滚动条时停止向下滚动?

Something like

就像是

       var int = self.setInterval("f2()", 1000);
       function f2() {
       var objDiv = document.getElementById("messages2");
       // if(objDiv.onscroll) i.e. when the particular DIV's scroll bar is on hold by cursor.
          {
          return false;
          }
       else
          {
            objDiv.scrollTop = objDiv.scrollHeight;
          }
      }

If the above kind of function can be implemented anybody please correct its syntax. I am a newbie to JavaScript.

如果任何人都可以实现上述类型的功能,请更正其语法。我是 JavaScript 的新手。

Thanks in advance..!

提前致谢..!

回答by David Hellsing

I'm not sure what you are asking here, but windowhas a scroll event that you can listen to, and so does any other element that has overflow: auto|scrollset using CSS.

我不确定您在这里问的是什么,但是window有一个可以收听的滚动事件,overflow: auto|scroll使用 CSS 设置的任何其他元素也是如此。

You can't prevent the default scrolling behavior, but you can use the scrollTo()method or the scrollTopproperty if you want to do something annoying like:

您无法阻止默认滚动行为,但是如果您想做一些烦人的事情,可以使用scrollTo()方法或scrollTop属性,例如:

window.onscroll = function() {
    window.scrollTo(0,0);
};

Here is a nice compat table of the scroll event: http://www.quirksmode.org/dom/events/scroll.html

这是滚动事件的一个很好的兼容表:http: //www.quirksmode.org/dom/events/scroll.html

scrollTo()docs: https://developer.mozilla.org/en/Window.scrollTo

scrollTo()文档:https: //developer.mozilla.org/en/Window.scrollTo