javascript - 如何在 React 中悬停时转换背景图像
问题描述
我的意图是在用户鼠标进入 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 属性不支持 CSS 选择器,例如:hover
. 另请注意,这&:hover
不是有效的 CSS,而是由您选择的 webpacker 预处理的有效 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)` }}
>
推荐阅读
- javascript - 在 apache 服务器上部署 React (3000) 和 Express (8000) 应用程序
- javascript - 使用 jest 比较两个文件的内容
- c++ - 在 C++11 中,可以在同一行声明全局变量和函数原型吗?
- sql - SQL - 如何在 where 子句中使用逗号分隔的列值
- python - insert() 缺少 1 个必需的位置参数:使用 python mysql 的“字符串”相同的错误
- powershell - IE11 停产后的 Web Bowser 自动化替代方案?
- javascript - 手风琴的动态高度
- linux - lsblk 命令使用 shell 命令或 shell 脚本将输出重定向到 csv 文件
- java - 异步 Servlet 请求负载均衡器超时
- botframework - 如何为“botframwork-webchat”中的每条传入消息添加侦听器