Commit c5c0ef53 by zhanghaozhe

banner

parent 34e7ac4d
import React, { Component } from 'react'
import './index.scss'
import { throttle } from 'lodash'
class Banner extends Component {
navTop = 183
prevY = 0
state = {
navs: [
{
text: '积福气'
text: '积福气',
id: 'lucky-value'
},
{
text: '幸运大抽奖'
text: '幸运大抽奖',
id: 'lucky-draw'
},
{
text: '预付定金'
text: '预付定金',
id: 'deposit'
},
{
text: '精品特惠'
text: '精品特惠',
id: 'best-courses'
},
{
text: 'AI测试'
text: 'AI测试',
id: 'ai-test'
},
{
text: '大咖直播'
text: '大咖直播',
id: 'live'
},
]
],
index: 0,
}
componentDidMount() {
window.addEventListener('scroll', throttle(this.calcNavActive, 100))
}
componentWillUnmount() {
}
calcNavActive = () => {
const {navs, index} = this.state
const y = window.scrollY
let swipeDirection = y > this.prevY ? 'up' : 'down'
let _index
if (swipeDirection === 'up') {
_index = (index + 1) >= navs.length ? index : index + 1
} else {
_index = (index - 1) <= 0 ? 0 : index - 1
}
let el = document.querySelector(`#${navs[_index].id}`)
let nav = document.querySelector('#main-nav')
let top = el.offsetTop
if (y <= this.navTop) {
nav.classList.remove('fixed')
} else {
!nav.classList.contains('fixed') && nav.classList.add('fixed')
}
if (swipeDirection === 'up') {
if (y + 30 + 30 >= top) {
this.setState({
index: _index
})
}
} else {
if (y + 30 + 20 <= top) {
this.setState({
index: _index
})
}
}
this.prevY = y
}
toSection = (i, e) => {
e.preventDefault()
let top = document.querySelector(`#${this.state.navs[i].id}`).offsetTop
this.setState({
index: i
})
window.scrollTo({
top: top - 60,
left: 0
})
}
render() {
const {navs} = this.state
const {navs, index} = this.state
return (
<div id={'main-banner'}>
<div className="banner"></div>
<nav id={'main-nav'}>
<ul>
{
navs.map((item, index) => {
navs.map((item, i) => {
return (
<li key={index}>{item.text}</li>
<li key={i} className={index === i ? 'active' : ''}>
<a href={`#${item.id}`} onClick={(e) => {
this.toSection(i, e)
}}>{item.text}</a>
</li>
)
})
}
......
#main-banner{
overflow: auto;
.banner{
width: 375px;
height: 183px;
......@@ -6,7 +7,14 @@
background-size: contain;
}
#main-nav{
position: absolute;
top: 183px;
margin-bottom:30px;
&.fixed{
position: fixed;
top: 0;
z-index: 100;
}
ul{
background: #3900C9;
display: flex;
......@@ -18,6 +26,9 @@
color: #fff;
text-align: center;
line-height: 30px;
&.active{
background: #FF42F9;
}
}
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment