论坛markdown还有点小问题,不能自动保存,哥哥们写文的时候记得先保存草稿,或者写好再复制粘贴上来T T
今天发现一个小游戏,感觉有点意思,大家能不能写一个小脚本来选择色块完成测试呢?
https://xingye.me/game/colortest/index.html
我先来
发现所有的元素都是在这个 div#box 这个盒子里
那总体思路就有了,监听这个盒子的变动再模拟点击就好了
我们使用MutationObserver去监听
详细的教程可看(论坛中直接搜索MutationObserver):
[油猴脚本开发指南]MutationObserver的使用
https://bbs.tampermonkey.net.cn/thread-988-1-1.html
[油猴脚本开发指南]MutationObserver简易例子
https://bbs.tampermonkey.net.cn/thread-1008-1-1.html
(再次推荐一下ScriptCat扩展,有基本的自动提示补全等功能,写小脚本直接用扩展写很是舒服,还可以格式化代码,让代码更加整洁!)
代码
// ==UserScript==
// @name New Userscript
// @namespace https://bbs.tampermonkey.net.cn/
// @version 0.1.0
// @description try to take over the world!
// @author You
// @match https://xingye.me/game/colortest/index.html
// @grant none
// ==/UserScript==
(function () {
'use strict';
// 找到盒子
let box = document.querySelector('div#box');
// 观察器的配置(需要观察什么变动)
const config = { attributes: true, childList: true, subtree: true };
// 当观察到变动时执行的回调函数
const callback = function (mutationsList, observer) {
for (let mutation of mutationsList) {
if (mutation.type === 'childList') {
// 找不同
let diffIndex = 0;
for (let index = 1; index < mutation.addedNodes.length; index++) {
if (mutation.addedNodes[0].getAttribute('style') != mutation.addedNodes[index].getAttribute('style')) {
diffIndex = index;
break;
}
}
if (diffIndex === 1) {
if (mutation.addedNodes[1].getAttribute('style') == mutation.addedNodes[2].getAttribute('style')) {
diffIndex = 0;
}
}
// 模拟点击
setTimeout(() => mutation.addedNodes[diffIndex].click(), 1000);
}
}
};
// 创建一个观察器实例并传入回调函数
const observer = new MutationObserver(callback);
// 以上述配置开始观察目标节点
observer.observe(box, config);
})();