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

4

我有一个包含图片的 <div> 元素。在这个 div 中,我有一个包含有关图片信息的 <p> 元素。我想悬停在包含图像的 <div> 上,然后显示或隐藏 <p> 元素。

<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中有没有一种简单的方法可以实现这一点?

你能提供一下你想做的HTML标记吗?我有点不清楚。 - Brad Gignac
抱歉,我刚忘记格式化代码了。 - mourique
4个回答

8
以下代码将匹配所有图片,并选中它们的第一个兄弟节点,该兄弟节点为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>

我也在做同样的事情,但我的段落大约有100行。因此,我必须向下滚动我的段落才能获取完整的内容。在这种情况下,当我将鼠标悬停在这里的A内容(图像)上时,内容会隐藏。我该怎么办? - Kavitha Velayutham

6
      $("css_selector_of_img").hover(
      function () {
        $("css_selector_of_p_element").show();
      },
      function () {
        $("css_selector_of_p_element").hide();
      }
      );

请查看 http://docs.jquery.com/Events/hover

我应该把这放在哪里?如果我在document.ready部分中写下这个,它会破坏我的其他js代码。 - mourique
将其放置在您的页面末尾,紧接着</body>,并用与使用document.ready相同的jQuery包围它,以便在<script></script>中运行。 - synhershko

3
$('#divwithimage').hover(
       function(){$('#ptag').show();}, //shows when hovering over
       function(){$('#ptag').hide();} //Hides when hovering finished
);

不要忘记逗号来分隔这两个函数。 - Sampson
我从 Firebug 得到了这个信息: 语句前缺少分号。 - mourique
可能是因为我在两个函数之间缺少了逗号。我刚刚尝试了一下,对我来说可以工作。 - AutomatedTester
现在没有错误了,但效果仍然不起作用。可能是因为我使用了包含和 PHP 开关来创建整个页面,导致 JavaScript 有点问题吗? - mourique

1
<div class="box">
    <img ... />
    <p class="hoverbox">Some text</p>
</div>

<script type="text/javascript">
    $('div.box img').hover(
        function() { $('div.box p.hoverbox').show(); },
        function() { $('div.box p.hoverbox').hide(); }
    );
</script>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接