[removed] scrollBy function executed on a div

2020-08-12 03:53发布

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

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

Uncaught TypeError: undefined is not a function

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

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

2条回答
啃猪蹄的小仙女
2楼-- · 2020-08-12 04:17

You can try this:

function scrollDiv(){
    document.getElementById("d").scrollTop += 100;
    document.getElementById("d").scrollLeft += 100;
}
查看更多
干净又极端
3楼-- · 2020-08-12 04:36

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'
})
查看更多
登录 后发表回答