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

如何实现鼠标悬停<p>元素时显示对应的textarea及相关内容

实现鼠标悬停触发反馈元素显示

需求:当鼠标悬停在<p>Would you like to give feedback?</p>元素上时,将<div id="Feedback">内的<p>How can we improve the page?</p>和<textarea>元素的display属性设置为block。

你的原始代码

HTML代码

<!DOCTYPE html>
<html>
  <head>
    <title>Sign up</title>
    <link href="./account.css" rel="stylesheet">
  </head>
  <body>
    <div id="entire-form">
      <form action="form.html" method="GET">
        <h1><b>Sign up =)</b></h1>
        <div id="Feedback">
                  <p>Would you like to give feedback?</p>
                  <p>How can we improve the page?</p>
                  <textarea name="improve" id="improve" rows="10" cols="70"></textarea>
        </div>
      </form> 
    </div>
  </body>
</html>

CSS代码

textarea, #Feedback p{
    display: none;
}

#Feedback p:nth-child(1) {
    /*What this does is it looks in the div with the id Feedback and its p elements and selects the first child i.e. the p that comes first*/
    display: block;
    margin: 15px;
}

#Feedback p:nth-child(1):hover{
    display: block;
}

解决方案

你当前的CSS仅处理了hover状态下第一个<p>的显示,没有对它的兄弟元素(第二个<p>和<textarea>)做任何修改。要实现需求,需要使用CSS兄弟选择器来选中这些后续元素。

修改后的CSS代码如下:

/* 初始状态:只显示第一个p,隐藏其他p和textarea */
#Feedback p:not(:first-child), #Feedback textarea {
    display: none;
}

#Feedback p:first-child {
    display: block;
    margin: 15px;
    cursor: pointer; /* 添加上手型光标,提示可交互 */
}

/* 鼠标悬停第一个p时,显示后续的p和textarea */
#Feedback p:first-child:hover ~ p,
#Feedback p:first-child:hover ~ textarea {
    display: block;
    margin: 15px 0;
}

代码说明

  1. :not(:first-child) 精准选中第一个p之外的所有同级p元素,配合textarea一起设置初始隐藏,逻辑更清晰。
  2. 给第一个p添加cursor: pointer,让用户更清楚这个元素是可交互的。
  3. 使用~兄弟选择器,选中第一个p之后的所有同级p和textarea元素,在hover状态下将它们的display设为block,实现悬停显示效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 08:52:17