悬停元素 A,显示/隐藏元素 B元素

2023-09-07 22:28:55 作者:幼稚园杀手

我有一个包含图像的 <div> 元素.在该 div 中,我有一个 <p> 元素,其中包含有关图像的一些信息.我想将包含图像的 <div> 悬停,然后显示或隐藏 <p> 元素.

I have a <div> element containing an image. Inside that div, I have a <p> element which holds some information about the image. I want to hover the <div> containing the image and then show or hide the <p> element.

<div class="box">
    <img src="img/an_039_AN_diskette.jpg" width="310px" height="465px" />
    6 Pharma IT
    <p class="hoverbox">some information</p>
</div>

在 jQuery 中有没有一种简单的方法可以做到这一点?

Is there an easy way to do so in jQuery?

推荐答案

以下内容将匹配您的所有图像,并以它们的第一个具有标签 P 的兄弟为目标.

The following will match all of your images, and target their first sibling having the tag P.

<script type="text/javascript">
$(document).ready(function(){
    $("div.box img").hover(
      function(){$(this).siblings("p:first").show();},
      function(){$(this).siblings("p:first").hide();}
    );
});
</script>

<div class="box">
  <img src="somefile.jpg" />
  <p>This text will toggle.</p>
</div>