feat: support BackTop[target], ref: #2718 (#2735)

This commit is contained in:
Benjy Cui 2016-08-18 11:28:00 +08:00 committed by 偏右
parent d28e193382
commit cf6643ae75

View File

@ -5,18 +5,21 @@ import addEventListener from 'rc-util/lib/Dom/addEventListener';
import classNames from 'classnames'; import classNames from 'classnames';
import omit from 'object.omit'; import omit from 'object.omit';
function getScroll(w, top) { function getScroll(target, top) {
let ret = w[`page${top ? 'Y' : 'X'}Offset`]; if (typeof window === 'undefined') {
const method = `scroll${top ? 'Top' : 'Left'}`; return 0;
if (typeof ret !== 'number') {
const d = w.document;
// ie6,7,8 standard mode
ret = d.documentElement[method];
if (typeof ret !== 'number') {
// quirks mode
ret = d.body[method];
}
} }
const prop = top ? 'pageYOffset' : 'pageXOffset';
const method = top ? 'scrollTop' : 'scrollLeft';
const isWindow = target === window;
let ret = isWindow ? target[prop] : target[method];
// ie6,7,8 standard mode
if (isWindow && typeof ret !== 'number') {
ret = window.document.documentElement[method];
}
return ret; return ret;
} }
@ -24,19 +27,23 @@ export default class BackTop extends React.Component {
static propTypes = { static propTypes = {
visibilityHeight: React.PropTypes.number, visibilityHeight: React.PropTypes.number,
target: React.PropTypes.func,
} }
static defaultProps = { static defaultProps = {
onClick() {}, onClick() {},
visibilityHeight: 400, visibilityHeight: 400,
target() {
return window;
},
prefixCls: 'ant-back-top', prefixCls: 'ant-back-top',
} }
constructor(props) { constructor(props) {
super(props); super(props);
const scrollTop = getScroll(window, true); const scrollTop = getScroll(props.target(), true);
this.state = { this.state = {
visible: scrollTop > this.props.visibilityHeight, visible: scrollTop > props.visibilityHeight,
}; };
} }
@ -47,19 +54,25 @@ export default class BackTop extends React.Component {
} }
setScrollTop(value) { setScrollTop(value) {
document.body.scrollTop = value; const targetNode = this.props.target();
document.documentElement.scrollTop = value; if (targetNode === window) {
document.body.scrollTop = value;
document.documentElement.scrollTop = value;
} else {
targetNode.scrollTop = value;
}
} }
handleScroll = () => { handleScroll = () => {
const scrollTop = getScroll(window, true); const { visibilityHeight, target } = this.props;
const scrollTop = getScroll(target(), true);
this.setState({ this.setState({
visible: scrollTop > this.props.visibilityHeight, visible: scrollTop > visibilityHeight,
}); });
} }
componentDidMount() { componentDidMount() {
this.scrollEvent = addEventListener(window, 'scroll', this.handleScroll); this.scrollEvent = addEventListener(this.props.target(), 'scroll', this.handleScroll);
} }
componentWillUnmount() { componentWillUnmount() {