簡體   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

我正在嘗試制作一個相當簡單的網格游戲,用戶必須單擊圖塊以顯示其下的內容。 我苦苦掙扎的第一個問題是實現點擊功能,該功能不僅會刪除被點擊的圖塊,還會刪除周圍的一些圖塊,最好是隨機的。

我當前的代碼:

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

非常感謝擴展我的簡單代碼的任何幫助。

您可以計算兄弟姐妹並隨機隱藏其中的一些兄弟姐妹,如下所示:

$('.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');
});

正如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');
    });

代碼增加了一點,因為我們必須控制是否不再有上一個或下一個同級,在這種情況下,請還原為其他同級。

如果您真正需要的是完全更復雜且控制更多的東西,請看以下示例(純javascript)

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM