如何仅为Ionic的ion-content添加动画 禁用ion-header动画并解决目标不生效问题
解决方法
根因说明
- 动画触发瞬间页面DOM还未完全挂载,直接查询
ion-content会返回空节点,动画无绑定目标自然不生效 - 原有代码直接给整个
enteringEl/baseEl(对应ion-page根节点)加动画,所以整页都会动
修改后可用代码
export const customAnimation = (baseEl: HTMLElement, opts: AnimationOptions) => { const rootTransition = animationCtrl .create() .duration(opts.duration || 3333) .easing('ease-in'); // 优先取ion-content作为动画目标,取不到回退到整页 const getContentEl = (el: HTMLElement) => { const content = el.querySelector('ion-content'); return content ? [content] : [el]; }; const enterTransition = animationCtrl .create() .addElement(getContentEl(opts.enteringEl)); const baseTransition = animationCtrl .create() .addElement(getContentEl(opts.baseEl)); if (opts.direction === 'forward' || opts.direction === 'root') { baseTransition.fromTo('transform', 'translateY(100%)', 'translateY(10%)').duration(500); enterTransition.fromTo('transform', 'translateY(10%)', 'translateY(100%)').duration(1000); } else { enterTransition.fromTo('transform', 'translateX(100%)', 'translateX(0%)'); } rootTransition.addAnimation([baseTransition, enterTransition]); return rootTransition; };
附加排查项
如果上述代码仍然不生效,按以下步骤检查:
- 给你的ion-content加唯一自定义类,比如
<ion-content class="custom-animate-content">,然后把查询逻辑改成el.querySelector('.custom-animate-content'),避免被嵌套容器拦截查询 - 检查ion-content是否设置了
overflow: visible,避免transform动画被截断 - 确认你使用的Ionic版本 >= 6,低版本自定义动画的元素绑定逻辑有兼容性问题
内容的提问来源于stack exchange,提问作者Mohammad Reza Mrg
相关产品推荐
相关产品推荐

