我正在尝试使用 Framer Motion 创建一个 React 网站,问题是我的动画在桌面视图中看起来不错,但在移动设备上却不太好。现在我想禁用动画。我该怎么做?
在不了解更多细节的情况下,我建议使用Variants。 在您的功能组件内,创建一个用于检查移动设备的变量。然后,仅在该变量为 false 时才填充变体。 请注意,调整页面大小时它不起作用。组件必须重新渲染。
有关变体的更多信息,查看本课程
当这个确切的问题出现时,我自己做了另一种简单的方法。下面我们使用三元运算符生成一个对象,然后使用扩展语法
扩展该对象const attributes = isMobile ? {
drag: "x",
dragConstraints: { left: 0, right: 0 },
animate: { x: myVariable },
onDragEnd: myFunction
} : { onMouseOver, onMouseLeave };
<motion.div {...attributes}> {/* stuff */} </motion.div>
如您所见,我希望 onMouseEnter 和 onMouseLeave 在桌面上没有动画。在移动设备上我想要相反的。这对我来说效果很好。 希望这也有帮助。
丹尼尔
我们就是这样做的:
import {
type ForwardRefComponent,
type HTMLMotionProps,
motion as Motion,
} from 'framer-motion';
import { forwardRef } from 'react';
const ReducedMotionDiv: ForwardRefComponent<
HTMLDivElement,
HTMLMotionProps<'div'>
> = forwardRef((props, ref) => {
const newProps = {
...props,
animate: undefined,
initial: undefined,
transition: undefined,
variants: undefined,
whileDrag: undefined,
whileFocus: undefined,
whileHover: undefined,
whileInView: undefined,
whileTap: undefined,
};
return <Motion.div {...newProps} ref={ref} />;
});
export const motion = new Proxy(Motion, {
get: (target, key) => {
if (key === 'div') {
return ReducedMotionDiv;
}
// @ts-expect-error - This is a proxy, so we can't be sure what the key is.
return target[key];
},
});
export {
AnimatePresence,
type Variants,
type HTMLMotionProps,
type MotionProps,
type TargetAndTransition,
type Transition,
type Spring,
} from 'framer-motion';
与其他答案相同的原理,只是完整的示例。
在这里发布有点晚了,但我也需要这样做,我通过使用 window
对象中的
matchMediaAPI 来整理它
const isMobile = window.matchMedia("(max-width: 992px)").matches
// now you can use this value to toggle animations ON/OFF
摘自他们的文档:
“Window接口的matchMedia()方法返回一个新的 然后可以使用 MediaQueryList 对象来确定是否 文档匹配媒体查询字符串,以及监控 文档来检测何时匹配(或停止匹配)该媒体 查询。”
希望这对某人有帮助;)
10.17.0之后可以使用MotionGlobalConfig:
import { MotionGlobalConfig } from 'framer-motion';
const disableAnimationsOnMobile = () => {
const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
if (isMobile) {
MotionGlobalConfig.skipAnimations = true;
}
};
https://github.com/framer/motion/issues/1604#issuecomment-1875508835