在悬停时显示一个随机元素,Jquery

时间:2011-06-20 10:40:27

标签: jquery html

我希望每次鼠标悬停在徽标上时都会显示一个随机的段落元素,并在鼠标离开时再次隐藏。

以下是段落和徽标的HTML:

<div>
<p class="quote" >ryan is a champion at indesign</p>
<p class="quote">ryan is not a champion at javascript</p>
<p class="quote">ryan likes ramen</p>
</div>

<a href="#"><img id="logo" src="../_blog/_assets/_logo_icons/_logo.png" alt="logo" /></a>

这个脚本是我迄今为止发现的最接近这个脚本的脚本:

$('p.quote').hide();

var quotes = $('p.quote');
var rand = Math.floor(Math.random() * quotes.length);

$('#logo').hover(function(){
    quotes.eq(rand).toggle();

    });

不幸的是,除非我刷新页面,否则每次只显示相同的引用。还有其他建议吗?

由于 莱恩

3 个答案:

答案 0 :(得分:2)

将从var rand开始的行移到悬停功能中而不是在其外部。

然后改变:

quotes.eq(rand).toggle();

要:

quotes.hide().eq(rand).show();

您还需要修改.hover(),以便在停止悬停时隐藏引用。

以下是完整代码:

var quotes = $('p.quote');

$('#logo').hover(
  function() {
    var rand = Math.floor(Math.random() * quotes.length);
    quotes.hide().eq(rand).show();
  },
  function() {
    quotes.hide()
  }
);

答案 1 :(得分:1)

在您的悬停处理程序中移动var rand = Math.floor(Math.random() * quotes.length);,如下所示:

$('#logo').hover(function(){
    var rand = Math.floor(Math.random() * quotes.length);
    quotes.eq(rand).toggle();

    });

这样,它每次都会更新你的兰特

答案 2 :(得分:0)

在这里工作小提琴:http://jsfiddle.net/wEnAW/7/