Merge pull request #3847 from 2betop/chore-aside-sticky

chore: 优化 aside styicky 的位置, 如果父级有 scroll 元素,之前的位置不对
This commit is contained in:
hsm-lv 2022-03-24 21:26:35 +08:00 committed by GitHub
commit 8c99dd1820
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 34 additions and 3 deletions

View File

@ -33,6 +33,8 @@ import mapValues from 'lodash/mapValues';
import {resolveVariable} from '../utils/tpl-builtin'; import {resolveVariable} from '../utils/tpl-builtin';
import {buildStyle} from '../utils/style'; import {buildStyle} from '../utils/style';
import PullRefresh from '../components/PullRefresh'; import PullRefresh from '../components/PullRefresh';
import position from '../utils/position';
import {scrollPosition} from '../utils/scrollPosition';
/** /**
* *
@ -385,8 +387,9 @@ export default class Page extends React.Component<PageProps> {
if (asideSticky && this.asideInner.current) { if (asideSticky && this.asideInner.current) {
const dom = this.asideInner.current!; const dom = this.asideInner.current!;
const rect = dom.getBoundingClientRect(); dom.style.cssText += `position: sticky; top: ${
dom.style.cssText += `position: sticky; top: ${rect.top}px;`; scrollPosition(dom).top
}px;`;
} }
} }

View File

@ -20,7 +20,6 @@ export default function position(
) { ) {
let parentOffset = {top: 0, left: 0}; let parentOffset = {top: 0, left: 0};
let offset; let offset;
getComputedStyle;
// Fixed elements are offset from window (parentOffset = {top:0, left: 0}, // Fixed elements are offset from window (parentOffset = {top:0, left: 0},
// because it is its only offset parent // because it is its only offset parent
if (getComputedStyle(node).getPropertyValue('position') === 'fixed') { if (getComputedStyle(node).getPropertyValue('position') === 'fixed') {

View File

@ -0,0 +1,29 @@
import position from './position';
function getScrollParent(element: HTMLElement | null, includeHidden?: boolean) {
if (!element) {
return document.body;
}
let style = getComputedStyle(element);
const excludeStaticParent = style.position === 'absolute';
const overflowRegex = includeHidden
? /(auto|scroll|hidden)/
: /(auto|scroll)/;
if (style.position === 'fixed') return document.body;
for (let parent = element; (parent = parent.parentElement!); ) {
style = getComputedStyle(parent);
if (excludeStaticParent && style.position === 'static') {
continue;
}
if (overflowRegex.test(style.overflow + style.overflowY + style.overflowX))
return parent;
}
return document.body;
}
export function scrollPosition(dom: HTMLElement) {
return position(dom, getScrollParent(dom));
}