如何根据父级悬停状态显示子级或其他子级(仅限CSS)



我正在react中构建一个显示选项列表的Menu组件。每个选项的左侧都有一个文本,">"图标。但是,当我将鼠标悬停在父对象上时,我想要">"符号更改为'>gt;'。我该怎么做?我已经添加了源的当前状态。我只需要在父悬停时隐藏BsChevronRight,并显示BsChevron DoubleRight和viceversa。

function Menu({data}:{data:IMenuItemData[]}) {
return (
<div className="w-2/12 flex flex-col absolute top-2/4">
{data.map(el => {
return <a href="#" className="flex row justify-between items-center group">
{el.text}
<BsChevronRight></BsChevronRight>
<BsChevronDoubleRight></BsChevronDoubleRight>
</a>

})}
</div>    

)
}

我正在寻找一个只支持CSS的解决方案。

为您的第二个V形(应该出现(或任何渐变效果添加hidden group-hover:block类,如:invisible group-hover:visibleopacity-0 group-hover:opacity-100。父a元素应该具有group类才能工作。

注意:如果您使用的是未启用jit模式的TailwindCSS,则需要扩展一些属性以支持group-hover变体

// tailwind.config.js
module.exports = {
variants: {
extend: {
display: ['group-hover'],
visibility: ['group-hover'],
}
}
}

演示:https://play.tailwindcss.com/XifyCwLkFV

好吧,我似乎找到了一个解决方案。这让我觉得有点生气,但它有效。诀窍是让一个父对象和两个子对象在none和block之间切换显示属性。

对我来说,它完成了任务。如果有人有更好的解决方案,我会洗耳恭听。

HTML:

<html>
<body>
<div class="parent">
Hello
<div class="child1"></div>
<div class="child2"></div>
</div>
</body>
</html>

CSS:

.parent {
width:300px;
height:300px;
background-color:yellow;
display:flex;
}
.parent:hover > .child1 {
display:block;
}
.parent:hover > .child2 {
display:none;
}
.child1 {
display:none;
width: 100px;
height:100px;
background-color: green;
}
.child2 {
display:block;
width: 100px;
height:100px;
background
}

https://jsfiddle.net/pyfL7r03/42/

在Tailwind中有一种快速的方法:

1.(添加一个";组";类到父类,例如

<div class="group i-am-parent">

2.(在子对象上添加悬停效果,前缀为组,例如

<div class="i-am-child group-hover:scale-110">

顺风文档中的更多信息:https://tailwindcss.com/docs/hover-focus-and-other-states

尝试创建状态isHovered并使用onMouseEnteronMouseLeave进行切换

function Menu({data}:{data:IMenuItemData[]}) {
const [isHovered , setIsHovered] = useState(false);
const handleMouseEnter = ()=>{
setIsHovered(true)
}
const handleMouseLeave = ()=>{
setIsHovered(false)
}
return (
<div className="w-2/12 flex flex-col absolute top-2/4">
{data.map(el => {
return <a onMouseEnter={handleMouseEnter} onMouseLeave={handleMouseLeave} href="#" className="flex row justify-between items-center group">
{el.text}
{!isHovered ? <BsChevronRight/> : 
<BsChevronDoubleRight/>}
</a>

})}
</div>    

)
}

相关内容

最新更新