你可以使用React来实现这个效果。首先,你需要创建两个组件,一个是背景图的组件,另一个是背景色的组件。然后在父组件中将它们组合在一起。

具体实现如下:

import React, { useState } from 'react';

// 背景图组件
const BackgroundImage = () => {
  return (
    <div
      style={{
        width: '500px',
        height: '300px',
        backgroundImage: 'url(背景图的URL)',
        backgroundSize: 'cover',
        position: 'relative',
      }}
    ></div>
  );
};

// 背景色组件
const BackgroundColor = () => {
  const [hovered, setHovered] = useState(false);

  const handleMouseEnter = () => {
    setHovered(true);
  };

  const handleMouseLeave = () => {
    setHovered(false);
  };

  return (
    <div
      style={{
        width: '500px',
        height: '300px',
        backgroundColor: hovered ? 'red' : 'transparent',
        position: 'absolute',
        top: '0',
        left: '0',
      }}
      onMouseEnter={handleMouseEnter}
      onMouseLeave={handleMouseLeave}
    ></div>
  );
};

// 父组件
const App = () => {
  return (
    <div>
      <BackgroundImage />
      <BackgroundColor />
    </div>
  );
};

export default App;

在这个例子中,BackgroundImage组件用于显示背景图,BackgroundColor组件用于显示背景色。BackgroundColor组件使用useState来追踪鼠标是否悬停在其中。当鼠标悬停时,背景色变为红色,否则为透明。App组件将这两个组件组合在一起,并在父元素中显示它们。

你需要将背景图的URL替换为你自己的背景图URL。同时,你可以根据需要调整宽度和高度

两个div块一个放置背景图一个放置背景色背景色的div在背景图div上鼠标悬停使背景颜色改变背景图改变react

原文地址: https://www.cveoy.top/t/topic/iLM2 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录