简体   繁体   中英

How to implement a click function for an element within a tiled grid that when clicked it & elements in it's proximity fade out

I am trying to make a fairly simple grid game where users have to click tiles to reveal content underneath. The first issue i'm struggling with is implementing a click function that would remove not only the tile clicked but also a few tiles around it, preferably random.

My current code:

        $('.layer img').click(function() {
            $(this).css ('display', 'none');
        });

Any help extending my simple code much appreciated.

You can count the siblings and randomly hide some of them, like so:

$('.layer img').click(function() {
     sib = $(this).siblings();
     rand = Math.floor((Math.random()*sib.length)+1);
     for (i=0;i<rand;i++) {
        sib.eq(i).css ('display', 'none');
     }
     $(this).css ('display', 'none');
});

I'm adding here enhanced version, as OP commented, to randomly select previous or next siblings, up to 5 five of them in total:

$('.layer img').click(function() {
         sib = $(this).siblings();
         rand = Math.floor((Math.random()*sib.length)+1);
         rand = Math.min(5,rand);
         aprev = $(this);
         anext = $(this);
         for (i=0;i<rand;i++) {
            if (Math.floor((Math.random()*2)+1) == 1 ) { //random go prev or next
               if (aprev.prev().length) {
                  aprev = aprev.prev();
                  aprev.css ('display', 'none');
               } else {
                  anext = anext.next();
                  anext.css ('display', 'none');
               }
            } else {
               if (anext.next().length) {
                  anext = anext.next();
                  anext.css ('display', 'none');
               } else {
                  aprev = aprev.prev();
                  aprev.css ('display', 'none');
               }
            }
         }
         $(this).css ('display', 'none');
    });

the code grew a bit because we have to control whether there are no more previous or next siblings, and in that case revert to the other.

If what you really need is something entirely more complex and with more control take a look at this example (pure javascript)

http://jsfiddle.net/FgQQg/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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