效果
代码
从 Cornify.com 加载一个 JS 文件,调用其中的 cornify_add()
方法时,会在页面中追加 p
标签,并在 DOM 中插入一个图标。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Key Detection</title>
<script type="text/javascript" src="http://www.cornify.com/js/cornify.js"></script>
</head>
<body>
<h1>输入暗号</h1>
<script>
const pressed = [],
secretCode = 'hello';
window.addEventListener('keyup', (e) => {
console.log(e.key);
pressed.push(e.key);
/*
start: 如果负数的绝对值大于数组的长度,则表示开始位置为第0位。
deleteCount:是 0 或者负数,则不移除元素。这种情况下,至少应添加一个新元素。
*/
// pressed.splice(-secretCode.length - 1, pressed.length - secretCode.length); //截取数组
// pressed.splice(0, pressed.length - secretCode.length); //截取数组
pressed.length > secretCode.length ? pressed.shift() : '';
if (pressed.join('').includes(secretCode)) { //判断是否符合暗号
console.log('DING DING!');
cornify_add();
}
console.log(pressed);
})
</script>
</body>
</html>