javascript - With React, how can I horizontally scroll to the selected item in a scrollable div? - Stack Overflow

The idea is to have a horizontal scrollable list, and when selecting an item, the list scrolls to that

The idea is to have a horizontal scrollable list, and when selecting an item, the list scrolls to that item, which should make the item centered in the list.

I have tried to create an example using React, but I struggle to calculate the scrollLeft value.

/

const scrollContainer = ReactDOM.findDOMNode(this.scrollRef);
const activeItem = ReactDOM.findDOMNode(this.activeRef);

const scrollRect = scrollContainer.getBoundingClientRect();
const activeRect = activeItem.getBoundingClientRect();
const activeWidth = activeRect.width;
const activeLeft = activeRect.left;
const activeRight = activeRect.right;
const scrollWidth = scrollContainer.scrollWidth;
const scrollLeft = scrollRect.left;

scrollContainer.scrollLeft = (scrollWidth / 2) + (activeLeft / 2) + (scrollLeft * 2);

Desired result:

The idea is to have a horizontal scrollable list, and when selecting an item, the list scrolls to that item, which should make the item centered in the list.

I have tried to create an example using React, but I struggle to calculate the scrollLeft value.

http://jsfiddle/remisture/zug42kh8/

const scrollContainer = ReactDOM.findDOMNode(this.scrollRef);
const activeItem = ReactDOM.findDOMNode(this.activeRef);

const scrollRect = scrollContainer.getBoundingClientRect();
const activeRect = activeItem.getBoundingClientRect();
const activeWidth = activeRect.width;
const activeLeft = activeRect.left;
const activeRight = activeRect.right;
const scrollWidth = scrollContainer.scrollWidth;
const scrollLeft = scrollRect.left;

scrollContainer.scrollLeft = (scrollWidth / 2) + (activeLeft / 2) + (scrollLeft * 2);

Desired result:

Share Improve this question edited Jul 18, 2018 at 13:22 Remi Sture asked Jul 18, 2018 at 13:03 Remi StureRemi Sture 13k5 gold badges27 silver badges38 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 4

JSFiddle

First of all, yeah, calculating:

scrollLeftPosition: activeRect.left - scrollRect.left - (scrollRect.width / 2) + (activeRect.width / 2)

Second. I changed manipulation with scrollLeft to "+=". As you should not just assign in your case, but take in account current scroll state.

scrollContainer.scrollLeft += this.state.scrollLeftPosition;

And the main point: you called this.centerActiveItem() before new state applied. this.setState is async function. You need to pass function to call it after updating state.

this.setState({}, callback);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744699505a4588694.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信