Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

css - how to make javascript scrollIntoView smooth?

In a react app, I have a method being called to bring a particular node into view as follows.

scrollToQuestionNode(id) {
        const element = document.getElementById(id);
        element.scrollIntoView(false);
}

The scroll happens fine, but the scroll action is a little jerky. How can I make it smooth? I don't see any options which I can give to scrollIntoView for the same.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This might help.

From MDN documentation of scrollIntoView You can pass in option instead of boolean.

scrollIntoViewOptions Optional
A Boolean or an object with the following options:
{
  behavior: "auto"  | "instant" | "smooth",
  block:    "start" | "center" | "end" | "nearest",
  inline:    "start" | "center" | "end" | "nearest",
}

So you can simply pass parameter like this.

scrollToQuestionNode(id) {
  const element = document.getElementById(id);
  element.scrollIntoView({ block: 'end',  behavior: 'smooth' });
}

Reference: https://developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...