简体   繁体   中英

Smoothly scroll element from current position

I have written the following code to scroll an element 20 more pixels to the right.

const button = document.getElementById('slide');

button.onclick = function () {
  document.getElementById('container').scrollLeft += 20;
};

How can I make the scrolling smooth? I have tried using Element#scroll like so:

const button = document.getElementById('slide');

button.onclick = function () {
  document.getElementById('container').scroll({
      left: += 20,
      behavior: smooth
  });
};

Am I able to do this?

You can use Element#scrollBy to scroll a certain amount from the current position.

button.onclick = function () {
  document.getElementById('container').scrollBy({
      left: 20,
      behavior: 'smooth'
  });
};

You have a syntax problem here.

+= is only correct for variables, not for properties because they don't have an initial value to update.

Here is what it should look like:

const button = document.getElementById('slide');
const container = document.getElementById('container')

button.onclick = function () {
  container.scroll({
      left: container.scrollLeft + 20,
      behavior: 'smooth'
  });
};

Is this what you are looking for?

From MDN:

scrollBy() scrolls by a particular amount, whereas scroll() scrolls to an absolute position in the document.

https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy

 const container = document.querySelector("#container"); const button = document.querySelector("#btnScroll"); button.addEventListener('click', e => { container.scrollBy({ left: 200, behavior: 'smooth' }); });
 #container { position: relative; max-width: 200px; overflow-x: scroll; display: flex; margin: 20px; } img { display: inline-block }
 <div id="container"> <img src="https://dummyimage.com/200x100/000/fff"> <img src="https://dummyimage.com/200x100/0f0/000"> <img src="https://dummyimage.com/200x100/00f/fff"> <img src="https://dummyimage.com/200x100/f00/fff"> </div> <button id="btnScroll">Scroll 200px</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM