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 badges1 Answer
Reset to default 4JSFiddle
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条)