如何用jQuery根据Div颜色序列显示按钮(Rails 5场景)
实现颜色序列校验并显示按钮的方案
嘿,这个彩蛋页面的想法挺有意思的!既然颜色切换已经搞定,那咱们只需要加个序列校验的逻辑就行,其实很简单,我给你一步步拆解:
第一步:给方块加位置标识
首先,给每个彩色方块加个data-index属性,对应它在序列里的位置(0到7),这样咱们能精准对应每个位置的正确颜色。比如你的HTML可以写成这样:
<div class="color-square" data-index="0"></div> <div class="color-square" data-index="1"></div> <div class="color-square" data-index="2"></div> <!-- ... 一直到data-index="7" --> <!-- 要显示的隐藏按钮 --> <button id="secret-button" style="display: none;">彩蛋解锁!</button>
第二步:定义核心逻辑
在你的jQuery代码里,咱们需要做这几件事:
- 预设正确的颜色序列
- 每次切换颜色后,校验所有方块的颜色是否匹配序列
- 根据校验结果显示/隐藏按钮
因为Rails 5默认用Turbolinks,所以咱们把代码包在turbolinks:load事件里,确保页面加载完成后执行:
$(document).on('turbolinks:load', function() { // 替换成你预设的正确颜色序列(8个颜色对应8个方块) const correctSequence = ["red", "green", "yellow", "orange", "purple", "blue", "pink", "brown"]; // 你原来的颜色切换数组 const backgrounds = ["red", "green", "yellow", "orange", "purple", "blue", "pink", "brown"]; // 校验序列的核心函数 function checkIfSequenceIsCorrect() { let allMatch = true; // 遍历每个方块,对比当前颜色和对应位置的正确颜色 $('.color-square').each(function() { const squareIndex = $(this).data('index'); // 用data属性存颜色名称,避免rgb值和颜色名转换的麻烦 const currentColor = $(this).data('current-color'); if (!currentColor || currentColor !== correctSequence[squareIndex]) { allMatch = false; return false; // 不匹配就直接跳出循环,不用继续检查了 } }); // 显示或隐藏按钮 if (allMatch) { $('#secret-button').show(); } else { $('#secret-button').hide(); } } // 初始化每个方块的默认颜色(可选,比如默认第一个颜色) $('.color-square').each(function() { const initialColor = backgrounds[0]; $(this).css('background-color', initialColor); $(this).data('current-color', initialColor); }); // 方块点击切换颜色的逻辑(修改你原来的代码,加上data属性存储颜色名) $('.color-square').on('click', function() { const currentColor = $(this).data('current-color'); let currentIndex = backgrounds.indexOf(currentColor); // 如果当前颜色不在数组里,默认从0开始切换 currentIndex = currentIndex === -1 ? 0 : currentIndex; // 切换到下一个颜色(循环切换) const nextColor = backgrounds[(currentIndex + 1) % backgrounds.length]; $(this).css('background-color', nextColor); $(this).data('current-color', nextColor); // 关键:把当前颜色名存在data属性里 // 每次切换后立即校验序列 checkIfSequenceIsCorrect(); }); // 页面加载完成后先校验一次(防止初始状态就匹配的情况) checkIfSequenceIsCorrect(); });
关键细节说明
- 用
data-current-color存颜色名:直接用css('background-color')会返回RGB值(比如rgb(255, 0, 0)),和咱们的颜色名字符串对比会出错,所以用data属性存颜色名称是最稳妥的方式。 data-index绑定位置:确保每个方块对应序列里的固定位置,不会搞混顺序。- 实时校验:每次点击切换颜色后立刻检查,保证按钮状态实时更新。
这样改完之后,当8个方块的颜色完全匹配你预设的correctSequence时,按钮就会自动显示出来啦!
内容的提问来源于stack exchange,提问作者Christian O'Rourke
相关产品推荐
相关产品推荐

