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.

259 lines
7.2 KiB

import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import addEventListener from 'rc-util/lib/Dom/addEventListener';
import classNames from 'classnames';
import shallowequal from 'shallowequal';
import omit from 'omit.js';
import getScroll from '../_util/getScroll';
import { throttleByAnimationFrameDecorator } from '../_util/throttleByAnimationFrame';
function getTargetRect(target): ClientRect {
return target !== window ?
target.getBoundingClientRect() :
{ top: 0, left: 0, bottom: 0 };
}
function getOffset(element: HTMLElement, target) {
const elemRect = element.getBoundingClientRect();
const targetRect = getTargetRect(target);
const scrollTop = getScroll(target, true);
const scrollLeft = getScroll(target, false);
const docElem = window.document.body;
const clientTop = docElem.clientTop || 0;
const clientLeft = docElem.clientLeft || 0;
return {
top: elemRect.top - targetRect.top +
scrollTop - clientTop,
left: elemRect.left - targetRect.left +
scrollLeft - clientLeft,
width: elemRect.width,
height: elemRect.height,
};
}
function noop() {}
function getDefaultTarget() {
return typeof window !== 'undefined' ?
window : null;
}
// Affix
export interface AffixProps {
/**
*
*/
offsetTop?: number;
offset?: number;
/** 距离窗口底部达到指定偏移量后触发 */
offsetBottom?: number;
style?: React.CSSProperties;
/** 固定状态改变时触发的回调函数 */
onChange?: (affixed?: boolean) => void;
/** 设置 Affix 需要监听其滚动事件的元素,值为一个返回对应 DOM 元素的函数 */
target?: () => Window | HTMLElement;
prefixCls?: string;
}
export default class Affix extends React.Component<AffixProps, any> {
static propTypes = {
offsetTop: PropTypes.number,
offsetBottom: PropTypes.number,
target: PropTypes.func,
};
scrollEvent: any;
resizeEvent: any;
timeout: any;
events = [
'resize',
'scroll',
'touchstart',
'touchmove',
'touchend',
'pageshow',
'load',
];
eventHandlers = {};
private fixedNode: HTMLElement;
constructor(props) {
super(props);
this.state = {
affixStyle: null,
placeholderStyle: null,
9 years ago
};
}
9 years ago
setAffixStyle(e, affixStyle) {
const { onChange = noop, target = getDefaultTarget } = this.props;
const originalAffixStyle = this.state.affixStyle;
const isWindow = target() === window;
if (e.type === 'scroll' && originalAffixStyle && affixStyle && isWindow) {
return;
}
if (shallowequal(affixStyle, originalAffixStyle)) {
return;
}
this.setState({ affixStyle }, () => {
const affixed = !!this.state.affixStyle;
if ((affixStyle && !originalAffixStyle) ||
(!affixStyle && originalAffixStyle)) {
onChange(affixed);
}
});
}
setPlaceholderStyle(placeholderStyle) {
const originalPlaceholderStyle = this.state.placeholderStyle;
if (shallowequal(placeholderStyle, originalPlaceholderStyle)) {
return;
}
this.setState({ placeholderStyle });
}