react 滚动到指定元素位置,类似锚点功能
2018-11-28 本文已影响0人
小明_4f28
组件
class HomeView extends Component {
scrollToAnchor = (anchorName) => {
if (anchorName) {
let anchorElement = document.getElementById(anchorName);
if(anchorElement) { anchorElement.scrollIntoView(); }
}
}
render() {
return (
<div>
<div className="android-be-together-section mdl-typography--text-center">
<div className="logo-font android-slogan">be together. not the same.</div>
<div className="logo-font android-sub-slogan">welcome to android... be yourself. do your thing. see what's going on.</div>
<div className="logo-font android-create-character">
<a href=""><img src="images/andy.png" /> create your android character</a>
</div>
<a onClick={()=>this.scrollToAnchor('screens')}>
<button className="android-fab mdl-button mdl-button--colored mdl-js-button mdl-button--fab mdl-js-ripple-effect">
<i className="material-icons">expand_more</i>
</button>
</a>
</div>
<div className="mdl-grid" style={{height: 800}}>
<a id="screens"></a>
跳到这里
<br />
</div>
</div>
);
}
}
export default HomeView;
scrollIntoView的语法
用法如下:
element.scrollIntoView();
element.scrollIntoView(true);
element.scrollIntoView(alignToTop);
element.scrollIntoView(scrollIntoViewOptions);
alignToTop是一个布尔值,true 元素对齐到祖先元素的顶部,false 元素对齐到祖先元素的底部,默认是true
scrollIntoViewOptions是一个布尔值或以下选项的对象:
{
behavior: 'auto' | 'instant' | 'smooth',
block: 'start' | 'end'
}