Skip to content

Commit

Permalink
feat: support BackTop[target], ref: ant-design#2718 (ant-design#2735)
Browse files Browse the repository at this point in the history
  • Loading branch information
benjycui authored and afc163 committed Aug 18, 2016
1 parent d28e193 commit cf6643a
Showing 1 changed file with 31 additions and 18 deletions.
49 changes: 31 additions & 18 deletions components/back-top/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,38 +5,45 @@ import addEventListener from 'rc-util/lib/Dom/addEventListener';
import classNames from 'classnames';
import omit from 'object.omit';

function getScroll(w, top) {
let ret = w[`page${top ? 'Y' : 'X'}Offset`];
const method = `scroll${top ? 'Top' : 'Left'}`;
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];
}
function getScroll(target, top) {
if (typeof window === 'undefined') {
return 0;
}

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;
}

export default class BackTop extends React.Component {

static propTypes = {
visibilityHeight: React.PropTypes.number,
target: React.PropTypes.func,
}

static defaultProps = {
onClick() {},
visibilityHeight: 400,
target() {
return window;
},
prefixCls: 'ant-back-top',
}

constructor(props) {
super(props);
const scrollTop = getScroll(window, true);
const scrollTop = getScroll(props.target(), true);
this.state = {
visible: scrollTop > this.props.visibilityHeight,
visible: scrollTop > props.visibilityHeight,
};
}

Expand All @@ -47,19 +54,25 @@ export default class BackTop extends React.Component {
}

setScrollTop(value) {
document.body.scrollTop = value;
document.documentElement.scrollTop = value;
const targetNode = this.props.target();
if (targetNode === window) {
document.body.scrollTop = value;
document.documentElement.scrollTop = value;
} else {
targetNode.scrollTop = value;
}
}

handleScroll = () => {
const scrollTop = getScroll(window, true);
const { visibilityHeight, target } = this.props;
const scrollTop = getScroll(target(), true);
this.setState({
visible: scrollTop > this.props.visibilityHeight,
visible: scrollTop > visibilityHeight,
});
}

componentDidMount() {
this.scrollEvent = addEventListener(window, 'scroll', this.handleScroll);
this.scrollEvent = addEventListener(this.props.target(), 'scroll', this.handleScroll);
}

componentWillUnmount() {
Expand Down

0 comments on commit cf6643a

Please sign in to comment.