开发者

Randomize CSS Classes using Jquery

开发者 https://www.devze.com 2022-12-10 13:26 出处:网络
I am fairly new to jQuery and I am trying to rotate 6 CSS classes .img .img1 .img2 .img3 .img4 .img5 Only one of these classes has \"display:block;\" the rest have \"display: none;\".

I am fairly new to jQuery and I am trying to rotate 6 CSS classes

.img
.img1
.img2
.img3
.img4
.img5

Only one of these classes has "display:block;" the rest have "display: none;".

I am trying to basically randomize the appearance of these classes - for these 6 classes - by making the current "display: block" goto "display: none" a开发者_开发技巧nd then another class change to "Display:block" each time the page loads ?

Would anyone be able to help ?


var ran = rand(0,5)
$('.img').hide();
$('.img' + ran).show();

Give all the elements 2 classes 1 'img' and then a unique class 'img1,img2 etc'


Just modify the class of all pictures exclude the one which was randomly choosen.

pseudo code:

var img_id = rand(0,5);

for (i=0;i<5; ++i)
{
   if (i!=img_id)
      $("image_"+img_id).class = hiddenclass;
}


Your question is unclear.

I assume that you're trying to randomly show all elements that match one of those classes.

You can generate a random number between 0 and 6 by writing parseInt(Math.random() * 6, 10).

You can therefore write something like this: (and change .img to .img0)

var indexToShow = parseInt(Math.random() * 6, 10);

for(var i = 0; i <= 6; i++) {
    if(i === indexToShow)
        $('.img' + i).show();
    else
        $('.img' + i).hide();
}

If you make another class (eg, .img) and add it to all of the elements, you could make it simpler:

$('.img').hide();
$('.img' + parseInt(Math.random() * 6, 10)).show()


Choose one to show, then hide them all, filter by the class you want to show, and display it. It will be easier if you give them all a common class, say img to make the global selection easier.

var showClass = '.img' + parseInt(Math.random() * 6, 10);

$('.img').hide().filter(showClass).show();


You can randomize your styles using JQuery. Look at this example on CodePen: http://codepen.io/aziev/pen/xwpREN

// put in this array your classes
classes = ['class1', 'class2', 'class3'];

max = classes.length - 1;
currentClass = Math.round(Math.random() * max);

// change '.block' to selector of your element
$('.block').addClass(classes[currentClass]);
0

精彩评论

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

关注公众号