You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

103 lines
2.3 KiB

9 years ago
import React from 'react';
import joinClasses from 'react/lib/joinClasses';
import rcUtil from 'rc-util';
function getScroll(w, top) {
var ret = w['page' + (top ? 'Y' : 'X') + 'Offset'];
var method = 'scroll' + (top ? 'Top' : 'Left');
if (typeof ret !== 'number') {
var d = w.document;
//ie6,7,8 standard mode
ret = d.documentElement[method];
if (typeof ret !== 'number') {
//quirks mode
ret = d.body[method];
}
}
return ret;
}
function getOffset(element) {
var rect = element.getBoundingClientRect();
var body = document.body;
var clientTop = element.clientTop || body.clientTop || 0;
var clientLeft = element.clientLeft || body.clientLeft || 0;
var scrollTop = getScroll(window, true);
var scrollLeft = getScroll(window);
return {
top: rect.top + scrollTop - clientTop,
left: rect.left + scrollLeft - clientLeft
};
}
9 years ago
var Affix = React.createClass({
getDefaultProps() {
return {
offset: 0
};
},
getInitialState() {
return {
affix: false,
affixStyle: null
9 years ago
};
},
handleScroll() {
var affix = this.state.affix;
var scrollTop = getScroll(window, true);
var elemOffset = getOffset(this.getDOMNode());
9 years ago
if (!affix && (elemOffset.top - this.props.offset) < scrollTop) {
9 years ago
this.setState({
affix: true,
affixStyle: {
top: this.props.offset,
left: elemOffset.left,
width: this.getDOMNode().offsetWidth
}
9 years ago
});
}
if (affix && (elemOffset.top - this.props.offset) > scrollTop) {
9 years ago
this.setState({
affix: false,
affixStyle: null
9 years ago
});
}
},
componentDidMount() {
this.scrollEvent = rcUtil.Dom.addEventListener(window, 'scroll', this.handleScroll);
this.resizeEvent = rcUtil.Dom.addEventListener(window, 'resize', this.handleScroll);
9 years ago
},
componentWillUnmount() {
if (this.scrollEvent) {
this.scrollEvent.remove();
}
if (this.resizeEvent) {
this.resizeEvent.remove();
}
9 years ago
},
render() {
var affix = this.state.affix ? 'ant-affix' : '';
9 years ago
var className = this.props.className;
return (
<div {...this.props}>
<div className={joinClasses(className, affix)} style={this.state.affixStyle}>
{this.props.children}
</div>
9 years ago
</div>
);
}
});
module.exports = Affix;