我的目的是在用户鼠标进入 1.5 时缩放我的背景图像,但我的尝试被证明是中止的。这是我的代码:
import React from 'react';
import Slider from './index';
import horizontalCss from './css/horizontal.scss';
import content from './content';
import SourceView from './SourceView';
import './css/styles.scss';
function Autoplay() {
return (
<div>
<Slider classNames={horizontalCss} autoplay={3000}>
{content.map((item, index) => (
<div
key={index}
style={{ background: `url('${item.image}') no-repeat center center`,
'&:hover': {
background: 'white',
transform: 'scale(1.5)',
}, }}
>
<div className="center">
<div className="textWrapper">
<h2>{item.title}</h2>
</div>
</div>
</div>
))}
</Slider>
</div>
);
}
export default Autoplay;
我必须做哪些调整才能完成这项工作
正如人们之前提到的,这不是 React 的问题; 相反,HTML 中的 style 属性不像:hover
那样支持 CSS 选择器。另请注意,&:hover
不是有效的 CSS,而是由您选择的网络打包程序预处理的有效 SCSS。
但是,<div>
的悬停特定样式不会对任何内容做出反应,因此可以将它们放在一个类中
.my-image-class {
background-repeat: no-repeat;
background-position: center;
&:hover {
background: white;
transform: scale(1.5);
}
}
然后,您可以在不悬停时切换背景图像
<div
key={index}
className="my-image-class"
style={{ background: `url('${item.image}') }}
>
奖励:你可能会想更进一步,也想让你的悬停图像反应,这个策略会失败。Kalabasa 有一个很好的答案,它使用动态 CSS 变量(MDN 文档(作为反应式类属性。
您可以在课堂上陈述您的背景,如下所示:
.my-image-class {
background-image: var(--my-image);
background-repeat: no-repeat;
background-position: center;
&:hover {
background-image: var(--hover-image);
transform: scale(1.5);
}
}
然后动态更改变量
<div
key={index}
className="my-image-class"
style={{ '--my-image': `url(path)`; '--hover-image': `url(other-path)` }}
>
内联样式不支持pseudo selectors
您需要将悬停样式 css 移动到styles.scss
并尝试使用className
或id
你在寻找这样的东西吗?Repro on stackblitz 当您悬停块时,它会缩放块。 以下是 Stackblitz 不起作用时的代码:
.css:
html, body, #app {
margin: 0;
padding: 0;
position: relative;
}
.app-component{
position: absolute;
width: 300px;
height: 200px;
background-image: url('https://picsum.photos/200/300');
background-size: cover;
border: 1px solid black;
top:100px;
left:100px;
}
.app-component:hover{
transform: scale(1.5);
transition:transform 1s linear;
}
.app:
import React, { Component } from 'react';
import { render } from 'react-dom';
import './style.css';
const App = () => {
return (
<div className="app-component">
</div>
);
}
render(<App />, document.getElementById('root'));
你需要在css中做到这一点,尽可能避免使用内联样式。