Javascript:在 div 上执行的 scrollBy 函数

Javascript: scrollBy function executed on a div

我有一个 div 和 overflow: scroll; 我想放一个按钮。当您按下它时,div 的内容会滚动。

类似于:

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>

这在 FF 中有效,但在 Chrome 中无效。在 Chrome 我得到

Uncaught TypeError: undefined is not a function

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

但是还有其他方法吗?我没有使用 jQuery,我宁愿不用。

你可以试试这个:

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

而不是

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

你会不会

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