繁体   English   中英

jquery将元素移动到随机顺序中

[英]jquery move elements into a random order

我试图以随机顺序显示一系列图像。 但是,我不希望任何单个项目重复,直到所有项目都被显示,所以我不想从数组中选择一个随机图像,而是取整个数组,随机化它,然后从第一个到第一个顺序选择最后一个元素 这是我的代码:

HTML:

<div id="tout4"
<img src="images/gallery01.jpg" class="img_lg"/>
<img src="images/gallery02.jpg" class="img_lg"/>
<img src="images/gallery03.jpg" class="img_lg"/>
</div>

和javascript,它当前按顺序选择和显示项目:

var galleryLength = $('#tout4 img.img_lg').length;
var currentGallery = 0;
setInterval(cycleGallery, 5000);


function cycleGallery(){

    $('#tout4 img.img_lg').eq(currentGallery).fadeOut(300);

    if (currentGallery < (galleryLength-1)){
        currentGallery++;
    } else {
        currentGallery = 0;
    }

    $('#tout4 img.img_lg').eq(currentGallery).fadeIn(300);
}

那么如何重新排列图像的实际顺序,而不仅仅是它们的选择顺序?

经过深入探索后,我决定采用fisher-yates算法并将其应用于jquery而无需克隆等。

$('#tout4 img.img_lg').shuffle();

/*
* Shuffle jQuery array of elements - see Fisher-Yates algorithm
*/
jQuery.fn.shuffle = function () {
    var j;
    for (var i = 0; i < this.length; i++) {
        j = Math.floor(Math.random() * this.length);
        $(this[i]).before($(this[j]));
    }
    return this;
};

您还可以使用常见的JavaScript数组随机分类器此处此处也进行了注释:

$('<my selector>').sort( function(){ return ( Math.round( Math.random() ) - 0.5 ) } );

结束使用此 (感谢Blair!) -

/**
 * jQuery Shuffle (/web/20120307220753/http://mktgdept.com/jquery-shuffle)
 * A jQuery plugin for shuffling a set of elements
 *
 * v0.0.1 - 13 November 2009
 *
 * Copyright (c) 2009 Chad Smith (/web/20120307220753/http://twitter.com/chadsmith)
 * Dual licensed under the MIT and GPL licenses.
 * /web/20120307220753/http://www.opensource.org/licenses/mit-license.php
 * /web/20120307220753/http://www.opensource.org/licenses/gpl-license.php
 *
 * Shuffle elements using: $(selector).shuffle() or $.shuffle(selector)
 *
 **/
(function(d){d.fn.shuffle=function(c){c=[];return this.each(function(){c.push(d(this).clone(true))}).each(function(a,b){d(b).replaceWith(c[a=Math.floor(Math.random()*c.length)]);c.splice(a,1)})};d.shuffle=function(a){return d(a).shuffle()}})(jQuery);

那么需要对上面的代码进行的唯一补充是包含脚本,并调用shuffle函数:

<script type="text/javascript" src="js/jquery-shuffle.js"></script>
$('#tout4 img.img_lg').shuffle();
<!DOCTYPE html>
<html>
<body>

<p id="demo">Click the button to sort the array.</p>

<button onclick="myFunction()">Try it</button>

<script>
  function myFunction()
  {
    var points = [40,100,1,5,25,10];
    points.sort(function(a,b){return (Math.random()-0.5)});
    var x=document.getElementById("demo");
    x.innerHTML=points;
  }
</script>

</body>
</html>

说明:通常你有“return(ab)”产生升序排序的正数; 或者你有“return(ba)”产生一个负数,用于降序排序。

这里我们使用Math.random() - 0.5,其中一半的情况给出正数,一半的情况给出一个负数。 因此,对的排序是上升或下降,产生阵列元素的随机分布。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM