admin管理员组文章数量:1391960
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);
本文标签:
版权声明:本文标题:javascript - With React, how can I horizontally scroll to the selected item in a scrollable div? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744699505a2620480.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论