gpt4 book ai didi

javascript - 悬停时旋转图像失败

转载 作者:行者123 更新时间:2023-12-05 00:30:54 25 4
gpt4 key购买 nike

我有一个在悬停时旋转图像的工作示例 here
它在将鼠标悬停在父元素上时使用 scale()、rotate() 和转换属性来为图像设置动画。
和溢出:隐藏在父元素上以隐藏图像变换的多余部分。
当我尝试在 React 上复制相同的效果时,我看到了图像,但是当我悬停时图像没有旋转。但都一样吗?我在这里想念什么?

import React from 'react';
import { Box } from '@mui/material';
import Image from 'mui-image';

const styles = {
hoverRotate: {
overflow: 'hidden',
margin: '8px',
minWidth: '240px',
maxWidth: '320px',
width: '100%',
},

'hoverRotate img': {
transition: 'all 0.3s',
boxSizing: 'border-box',
maxWidth: '100%',
},

'hoverRotate:hover img': {
transform: 'scale(1.3) rotate(5deg)',
},
};

function Rotate() {
return (
<Box style={styles.hoverRotate}>
<Image src="https://picsum.photos/id/669/600/800.jpg" />
</Box>
);
}

export { Rotate };

最佳答案

这种样式不会检测悬停,因此使用 useState设置图像的悬停状态(使用 import { useState } from "react"; 导入)

const [isHover, setIsHover] = useState(false);
现在,检查 Box是否悬停,如果悬停,设置 isHovertrue ,如果未悬停,则将其设置为 false .
<Box
style={styles.hoverRotate}
onMouseEnter={() => setIsHover(true)}
onMouseLeave={() => setIsHover(false)}
>
{/* code */}
</Box>
移动您的 styles进入 Rotate功能。您没有分配 key "hoverRotate img"任何样式,因此它不会被应用。所以把它的名字改成 image并有条件地向其添加悬停代码,如下所示。搬家原因 styles进入 Rotate使 isHover保持在范围内以获得它的值(value)。
const styles = {
hoverRotate: {
overflow: "hidden",
margin: "8px",
minWidth: "240px",
maxWidth: "320px",
width: "100%"
},

image: {
transition: "all 0.3s",
boxSizing: "border-box",
maxWidth: "100%",
transform: isHover && "scale(1.3) rotate(5deg)"
}
};
最后,设置 image样式到 Image
<Image
src="https://picsum.photos/id/669/600/800.jpg"
style={styles.image}
/>

查看此沙盒: https://codesandbox.io/s/distracted-matan-c43ufb?file=/src/App.js:829-928

关于javascript - 悬停时旋转图像失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73086940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com