简体   繁体   English

如何为平铺网格中的元素实现单击功能,当单击该元素及其附近的元素时淡出

[英]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: 正如OP所评论的,我在这里添加了增强版本,以随机选择上一个或下一个兄弟姐妹,总共最多五个5:

$('.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) 如果您真正需要的是完全更复杂且控制更多的东西,请看以下示例(纯javascript)

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

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

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