Skip to content

Instantly share code, notes, and snippets.

@swcho
Created July 8, 2017 05:43
Show Gist options
  • Select an option

  • Save swcho/a27228fc99cf54cfdebc8011c31fe8f2 to your computer and use it in GitHub Desktop.

Select an option

Save swcho/a27228fc99cf54cfdebc8011c31fe8f2 to your computer and use it in GitHub Desktop.
Float Menu
@import './variables.less';
:local .root {
float: left;
text-align: left;
width: 208px;
height: auto;
padding-left: 10px;
&.scrollOverTop {
position: fixed;
top: 98px + 71px; // Header Height
}
&.scrollOverHeight {
border-left: 1px solid @color_border;
box-sizing: border-box;
overflow-y: scroll;
}
}
import React = require('react');
import S = require('./floatmenu.less');
const HEADER_HEIGHT = 98;
export class FloatMenu extends React.Component<{}, {
scrollOverTop?: number;
scrollOverHeight?: number;
}> {
constructor(props) {
super(props);
this.handleScroll = this.handleScroll.bind(this);
this.state = {
scrollOverTop: 0,
scrollOverHeight: 0
};
}
render() {
const {
scrollOverTop,
scrollOverHeight
} = this.state;
const classNames = [S.root];
const fixedStyle = {};
if (scrollOverTop) {
classNames.push(S.scrollOverTop);
fixedStyle['top'] = scrollOverTop + 'px';
}
if (scrollOverHeight) {
classNames.push(S.scrollOverHeight);
fixedStyle['height'] = scrollOverHeight;
}
return (
<div className={classNames.join(' ')} ref='root' style={fixedStyle}>
{this.props.children}
</div>
);
}
handleScroll(evt) {
const elRoot: HTMLElement = this.refs['root'] as any;
if (!elRoot) {
return;
}
const height = elRoot.clientHeight;
const elParent: HTMLElement = elRoot.parentElement;
const parentRect = elParent.getBoundingClientRect();
const parentHeight = parentRect.height;
const parentTop = parentRect.top;
const parentBottom = parentRect.bottom;
// const scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
const PADDING_TOP = 130;
const PADDING_BOTTOM = 30;
let scrollOverTop = 0;
let scrollOverHeight = 0;
if (height < parentHeight) {
if (parentTop < HEADER_HEIGHT) {
scrollOverTop = PADDING_TOP;
const windowHeight = window.innerHeight;
const div = parentBottom - windowHeight;
const screenHeight = windowHeight - PADDING_TOP;
if (div < 0) {
scrollOverHeight = screenHeight + div;
} else {
scrollOverHeight = screenHeight - PADDING_BOTTOM;
}
}
}
if (this.state.scrollOverTop !== scrollOverTop || this.state.scrollOverHeight !== scrollOverHeight) {
this.setState({
scrollOverTop,
scrollOverHeight
});
}
}
componentDidMount() {
console.log('FLoatMenu.componentDidMount')
setTimeout(() => {
window.addEventListener('scroll', this.handleScroll);
}, 1000);
}
componentWillUnmount() {
window.removeEventListener('scroll', this.handleScroll);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment