开发者

How to make JavaScript Math.random Repeat?

basically i have a page on my site with boxes that slide to reveal a background color. I want this background color to be random on load of page by adding a class to the element, eg .blue, .green etc...

I have created this code and as you may notice this randomly sorts the color class and applies to the element, this works for the first 6 elements however this page in particular has 12 elements i wish this to apply to, so my question is how do i apply a random selection of the variable classes to all ".portfolio ul li a "? Would it need to have some form of a repeat?

This is my script ..

function randCol() {
return (Math.round(Math.random())*7); }

$(document).ready(function() {
var classes = [ 'blue', 'orange',开发者_StackOverflow 'green', 'pink', 'black', 'white'];
classes.sort( randCol );
$('.portfolio ul li a').each(function(i, val) {
    $(this).addClass(classes[i]);
});

})

This is my source code structure

<div class="portfolio">
<ul>
    <li>
       <a href="#">
         <img src="images/content/portfolio/sample1.png" height="175" width="294" alt="sample" class="front" />
         Text for behind the image                         
       </a>
    </li>


Your randCol() comparison function doesn't really work. In the first place, such a function should return 1, -1 or 0 depending on whether the first term of the comparison is greater than, less than, or equal to (respectively) the second term.

Second, the code you have in there is apparently intended to reference your 6-element array, but as written it can return values as high as 7, which is 2 higher than the last index of the array. Better to do your randoming within the each() function literal, like so:

$(document).ready(function() {
var classes = [ 'blue', 'orange', 'green', 'pink', 'black', 'white'];

$('.portfolio ul li a').each(function(i, val) {
    var index = Math.floor(Math.random()*6); // highest value will be 5, lowest will be 0
    $(this).addClass(classes[index]);
});


the above answer may result in repetition of clours I think this can fix it :)

$(document).ready(function() {
var classes = [ 'blue', 'orange', 'green', 'pink', 'black', 'white'];
var temp=0;
$('.portfolio ul li a').each(function(i, val) {
    if(temp==0){
    var index = Math.floor(Math.random()*6);}
    else{ 
    var index = Math.floor(Math.random()*6);
    index=temp+index;
    temp=index;}
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜