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