【问题标题】:jquery hover functionjquery悬停功能
【发布时间】:2013-02-22 11:30:57
【问题描述】:

如何更改以下代码,以便当 onmouseover 事件触发时,超链接的右侧会出现一个 div?

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>

<script>
$(document).ready(function(){
$('a.moreDetails').hover(function() {
$(this).next().toggle('fast');
});
});

</script>  

<body>
<a href="#" class="moreDetails">(details)</a>
<div class="details">User 1</div>
</body>
</html>

【问题讨论】:

    标签: jquery html css mouseover


    【解决方案1】:

    jQuery 的 hover 方法有两个函数输入:

    $("a.moreDetails").hover(
      function(){
        $(this).next().show('fast');
      },
      function(){
        $(this).next().hide('fast');
      }
    );
    

    您似乎还缺少结束 &lt;/head&gt; 标记。让您的元素出现在您的链接旁边将需要一些标记更改、javascript 操作或一些 css 规则。你可以做这个小改动:

    <a href="#" class="moreDetails">(details)</a>
    <span class="details">User 1</span>
    

    【讨论】:

    • 谢谢...但是如何让它出现在超链接旁边
    • @Hulk:您可以将其从 div 更改为 span,或者您可以将 display:inline 添加到其样式中。
    【解决方案2】:

    hover 需要 2 个函数作为参数,来处理 over 和 out。你应该在第一个中显示并在第二个中隐藏。那么你的 div,除非它的类使它内联,否则应该是一个跨度

    【讨论】:

      【解决方案3】:

      hover() 有两个参数:激活时的回调和停用时的回调:

      $("a.moreDetails").hover(function() {
        $(this).next("div.details").stop().show("fast");
      }, function() {
        $(this).next("div.details").stop().show("slow");
      });
      

      你会注意到我打电话给stop()。这是使用动画时养成的好习惯,否则您可能会从排队动画中获得意想不到的视觉伪影。

      编辑:出现在元素旁边有一些困难。您可以更改 CSS:

      div.details { display: inline; }
      

      它会出现在链接旁边,但是 jQuery 效果将无法真正正常工作,因为它们倾向于将内容设置为 display: block。如果您不想要或不需要这种效果,您可以使用一个类:

      div.details { display: inline; }
      div.hidden { display: none; }
      

      然后:

      $("a.moreDetails").hover(function() {
        $(this).next("div.details").addClass("hidden");
      }, function() {
        $(this).next("div.details").removeClass("hidden");
      });
      

      【讨论】:

      • 谢谢...但是如何让它出现在超链接旁边而不是下方