1.div跟随鼠标移动(键盘事件和鼠标事件)
<!-- <script>
//键盘事件
window.onload = function () {
var box1 = document.querySelector(".box1");
//为document绑定一个按键按下的事件
document.onkeydown = function (event) {
/*keyCode中 37左,38上,39右,40下 */
// console.log(event.keyCode);
var speed = 10;
switch (event.keyCode) {
case 37:
box1.style.left = box1.offsetLeft - speed + "px";
break;
case 38:
box1.style.top = box1.offsetTop - speed + "px";
break;
case 39:
box1.style.left = box1.offsetLeft + speed + "px";
break;
case 40:
box1.style.top = box1.offsetTop + speed + "px";
break;
}
};
};
</script> -->
<script>
//鼠标移动事件
window.onload = function () {
let box1 = document.querySelector('.box1');
document.addEventListener('mousemove', function (event) {
let x = event.clientX;
let y = event.clientY;
box1.style.left = `${x}px`;
box1.style.top = `${y}px`
}, false)
}
</script>
</head>
<body>
<div class="box1"></div>
</body>
2.验证码
<body>
<div class="v_code">
<div class="code_show">
<span class="code" id="checkCode"></span>
<!--通过js随机动态改变的-->
<a id="linkbt">看不清换一张</a>
</div>
<div class="input_code">
<label for="inputCode">验证码:</label>
<input type="text" id="inputCode" />
</div>
<input id="Button1" type="button" value="确定" />
</div>
<script>
//1.生成验证码
let code = document.querySelector('.code');
let linkbt = document.querySelector('#linkbt');
let str = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let yan = '';
function getRandom() {
for (let i = 0; i < 6; i++) {
let random = parseInt(Math.random() * str.length);
yan += str[random]
}
code.innerHTML = yan;
console.log(code.innerHTML, 'code');
}
getRandom()
//2、点击看不清验证码,重新生成
linkbt.addEventListener('click', function () {
yan = '';
getRandom();
}, false)
//3.进行验证 点击按钮时,进行对对比
let inputCode = document.querySelector('#inputCode');
let btn = document.querySelector('#Button1');
Button1.addEventListener('click', function () {
if (inputCode.value == '') {
alert('输入不能为空值');
} else if (inputCode.value == code.innerHTML) {
alert('验证成功');
} else {
alert('验证失败');
}
}, false)
</script>
标签:练习题,function,code,高级,JS,let,document,box1,event
From: https://blog.csdn.net/m0_74350516/article/details/145167818