You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React+Tailwind CSS实现hover a元素时同步触发h1元素透明度变化

实现方案

方案1:使用Tailwind内置的group-hover(推荐,无额外JS)

  • 实现逻辑:将a和h1包裹在同一个设置了group类的父元素下,所有需要在父元素被hover时触发的样式都加上group-hover:前缀即可。
  • 注意父容器需要设置relative定位,匹配你原有绝对定位子元素的布局。
import React from 'react'

function YourComponent() {
  return (
    {/* 父容器新增group和relative类 */}
    <div className="relative group">
      <a 
        href="#" 
        className="absolute inset-0 z-10 flex flex-col items-center justify-center duration-300 opacity-0 bg-planbau-blue group-hover:opacity-75 bg-opacity-90"
      ></a>
      <h1 
        className="absolute inset-x-0 z-20 tracking-wider text-white max-w-max text-sn md:text-2xl left-4 top-4 opacity-0 duration-300 group-hover:opacity-100"
      >
        test
      </h1>
    </div>
  )
}

你可以按需修改group-hover:后面绑定的样式,透明度、颜色、位移等Tailwind支持的属性都可以通过加该前缀实现联动。

方案2:使用React状态控制(适合元素无法放在同一个父容器的场景)

  • 实现逻辑:通过React state存储a元素的hover状态,监听a的onMouseEnter和onMouseLeave事件更新状态,再把状态绑定到h1的类名上控制样式即可。
import React, { useState } from 'react'

function YourComponent() {
  const [isHoverLink, setIsHoverLink] = useState(false)

  return (
    <>
      <a 
        href="#" 
        className="absolute inset-0 z-10 flex flex-col items-center justify-center duration-300 opacity-0 bg-planbau-blue hover:opacity-75 bg-opacity-90"
        onMouseEnter={() => setIsHoverLink(true)}
        onMouseLeave={() => setIsHoverLink(false)}
      ></a>
      <h1 
        className={`absolute inset-x-0 z-20 tracking-wider text-white max-w-max text-sn md:text-2xl left-4 top-4 duration-300 ${isHoverLink ? 'opacity-100' : 'opacity-0'}`}
      >
        test
      </h1>
    </>
  )
}

内容的提问来源于stack exchange,提问作者juhend23d

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 14:36:04