Javascript:在 div 上执行的 scrollBy 函数

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

Javascript: scrollBy function executed on a div

javascriptscroll

提问by Jeni

I have a div with overflow: scroll;And I would like to put a button. When you press it, the content of the divscrolls.

我有一个 divoverflow: scroll;并且我想放一个按钮。当你按下它时,div滚动的内容。

Something like:

就像是:

function scrollDiv() {
  document.getElementById("d").scrollBy(100, 100);
}
<div id="d">
  <p>Click the button to scroll by 100px.</p>
  <button onclick="scrollDiv()">Click me to scroll!</button>
</div>

This works in FF, but not in Chrome. In Chrome I get

这适用于 FF,但不适用于 Chrome。在 Chrome 我得到

Uncaught TypeError: undefined is not a function

未捕获的类型错误:未定义不是函数

The scrollByfunction seems to be defined as windowfunction, so I guess this is the problem, and it's working in FF not by standard.

scrollBy函数似乎被定义为window函数,所以我想这就是问题所在,它在 FF 中不是按标准工作的。

But is there another way to do that? I am not using jQuery, and I'd rather not.

但是还有其他方法可以做到这一点吗?我没有使用 jQuery,我宁愿不使用。

回答by Pavel

You can try this:

你可以试试这个:

function scrollDiv(){
    document.getElementById("d").scrollTop += 100;
    document.getElementById("d").scrollLeft += 100;
}

回答by Andy Wilson

Rather than do

而不是做

function scrollDiv(){
   document.getElementById("d").scrollTop += 100;
   document.getElementById("d").scrollLeft += 100;
}

would you not do

你不做吗

document.getElementById("d").scrollBy({
   top: 100,
   left: 100,
   behaviour: 'smooth'
})