【问题标题】:JQuery - hide a set of divs/images one by one randomlyJQuery - 随机一个一个隐藏一组div /图像
【发布时间】:2011-04-12 12:43:23
【问题描述】:

我有一组可见的 div/或图像。通过单击一个项目,我想隐藏其他 div/图像。不过应该是
- 随机
- 一个一个地使用 fadeOut() 或 hide()。
- (可能是动画)

我的 HTML:

<DIV class="myDivBox">Box no 1</DIV>
<DIV class="myDivBox">Box no 2</DIV>
<DIV class="myDivBox">Box no 3</DIV>
<DIV class="myDivBox">Box no 4</DIV>

<DIV class="myDivBox">Box no 5</DIV>
<DIV class="myDivBox">Box no 6</DIV>
<DIV class="myDivBox">Box no 7</DIV>
<DIV class="myDivBox">Box no 8</DIV>

<DIV class="myDivBox">Box no 9</DIV>
<DIV class="myDivBox">Box no 10</DIV>
<DIV class="myDivBox">Box no 11</DIV>
<DIV class="myDivBox">Box no 12</DIV>

到目前为止我的代码:

$(document).ready(function(){
    // I know, this will hide all items of class .itembox
    $(".item_box").click(function (event)
    {

        $(".item_box").random().fadeOut(); // using a random class to hide 

    });
});

我正在使用github提供的随机插件:

(function($) 
{
  jQuery.fn.random = function(num) {
  num = parseInt(num);
  if (num > this.length) return this.pushStack(this);
  if (! num || num < 1) num = 1;
  var to_take = new Array();
  this.each(function(i) { to_take.push(i); });
  var to_keep = new Array();
  var invert = num > (this.length / 2);
  if (invert) num = this.length - num;
  for (; num > 0; num--) {
  for (var i = parseInt(Math.random() * to_take.length); i > 0; i--)
  to_take.push(to_take.shift());
  to_keep.push(to_take.shift());
}
if (invert) to_keep = to_take;
return this.filter(function(i) { return $.inArray(i, to_keep) != -1; });
};
}) (jQuery);

有没有办法即使没有随机插件也能做到这一点? 谢谢

【问题讨论】:

  • 你的意思是让 'item_box' 和 'myDivBox' 使用相同的类吗?
  • 对不起,我的意思是“myDivBox”。谢谢!

标签: jquery animation random


【解决方案1】:

这将在您单击item_box 元素时随机隐藏其中一个可见框:

$(function(){
  $(".item_box").click(function() {
    var $visible = $(".myDivBox:visible");
    $visible.eq(Math.floor(Math.random() * $visible.length)).hide('slow');
  });
});

这将在五秒内随机选择时间隐藏所有框:

$(function(){
  $(".item_box").click(function() {
    $(".myDivBox").each(function(i, e){
      window.setTimeout(function() {
        $(e).hide('slow');
      }, Math.random() * 5000);
    });
  });
});

【讨论】:

  • 非常好!测试任何工作顺利。谢谢(错字:Math.random...)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-07-30
  • 1970-01-01
  • 2015-07-21
  • 2015-03-03
  • 2011-02-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多