实战首页:“回到顶部”功能实现

317 阅读2分钟

实现回到顶部和滚动到下方才显示控件的功能。

1. 回到顶部

回到顶部的逻辑很简单,利用 window 对象实例的 scroll 方法就可以了。我们需要添加一个触发 Div:

在 Home 组件中:

render() {
  return (
    <HomeWrapper>
      <HomeLeft>
        <img className='banner-img'
             src='https://upload-images.jianshu.io/upload_images/13448242-20871e9f865fb242.jpg?imageMogr2/auto-orient/strip|imageView2/2/w/594/format/webp'
             alt=''/>
        <Topic/>
        <List/>
      </HomeLeft>
      <HomeRight>
        <Recommend/>
        <Writer/>
      </HomeRight>
      <BackTop onClick={this.handleScrollTop}>顶部</BackTop>
    </HomeWrapper>
  );
}

// CSS
export const BackTop = styled.div`
  position:fixed;
  right:100px;
  bottom:30px
  width:60px;
  height:60px;
  line-height:60px;
  text-align:center;
  border: 1px solid #ccc;
  font-size:14px;
`;

//UI组件也可以有少量逻辑
handleScrollTop() {
  window.scroll(0, 0);
}

2. 滚动到下方才显示控件

接下来我们需要模仿简书,当回到顶部之后隐藏,滚动到下面才显示。首先需要添加一个 state 表示是否显示:

jsxCopy code
const defaultState = fromJS({
  topicList: [],
  articleList: [],
  recommendList: [],
  articlePage: 1,
  showScroll: false
});

然后绑定窗口的 scroll 事件来触发,并根据当前的 scrollTop 值来判断是否需要显示这个控件:

bindEvents() {
  //绑定事件于指定函数
  window.addEventListener('scroll', this.props.changeScrollTopShow);
}

componentDidMount() {
  this.props.changeHomeData();
  this.bindEvents();
}

componentWillUnmount() {
  //记得取消绑定,这样不会影响其他组件
  window.removeEventListener('scroll', this.props.changeScrollTopShow);
}

const mapDispatchToProps = (dispatch) => ({
  changeScrollTopShow() {
    // console.log(document.documentElement.scrollTop);
    if (document.documentElement.scrollTop > 200) {
      dispatch(actionCreators.toggleTopShow(true));
    } else {
      dispatch(actionCreators.toggleTopShow(false));
    }
  }
});

看一下对应的 action:

export const toggleTopShow = (show) => ({
  type: constants.TOGGLE_SCROLL_TOP,
  show
});

export default (state = defaultState, action) => {
  switch (action.type) {
    ...
    case constants.TOGGLE_SCROLL_TOP: {
      return state.set('showScroll', action.show);
    }
    default: {
      return state;
    }
  }
}

至此,回到顶部和滚动到下方才显示控件的功能已经实现了。

3. 总结

前端实现“回到顶部”功能的思路如下:

  1. 绑定一个“回到顶部”的按钮 在页面中添加一个按钮,并绑定一个点击事件。
  2. 实现回到顶部的逻辑 在点击事件中,利用 window 对象的 scroll 方法,将当前的滚动位置设置为 0,即回到页面顶部。
  3. 控制“回到顶部”的显示与隐藏 使用 CSS 样式控制按钮的位置、大小、颜色等外观,同时在滚动页面时动态修改按钮的显示状态。可以监听页面的滚动事件,通过获取当前滚动位置来判断是否需要显示按钮。