<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
div{
width: 100px;
height: 100px;
background-color: yellowgreen;
position: absolute;
}
</style>
</head>
<body style="height: 100vh;width: 100%;position: relative;">
<div id="box"></div>
<script>
/*
1, 鼠标点击某处, 让精灵移动到该处
2, 鼠标移动时, 让精灵跟随鼠标移动
*/
// 1
var box = document.getElementById('box')
var body = document.getElementsByTagName('body')[0]
body.onclick = function(e){
e = e || window.event
console.log(e.pageX)
box.style.top = e.pageY + "px"
box.style.left = e.pageX + "px"
}
// 2
body.onmousemove = function(e){
e = e || window.event
var x = e.pageX - box.clientWidth/2
var y = e.pageY - box.clientHeight/2
box.style.top = y + "px"
box.style.left = x + "px"
}
</script>
</body>
</html>
效果:
有一个红色的div块
1, 如果我按下ctrl + c变换颜色
2, 如果我按下ctrl + shift + ? 重置颜色, 恢复初始颜色
3, 如果我按下向上箭头, 向上移动, 同理还可以向下, 左, 右移动
4, 如果我按下ctrl + 上下左右, 走的步数变大
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0;
padding: 0;
}
div{
width: 100px;
height: 100px;
margin: 200px;
background-color: red;
/* transform: translate(100px,100px); */
position: absolute;
transition: all 0.1s linear;
}
</style>
</head>
<body style="position: relative;width: 100%;height: 100vh;">
<div id="box"></div>
<script>
/*
有一个红色的div块
1, 如果我按下ctrl + c变换颜色
2, 如果我按下ctrl + shift + ? 重置颜色, 恢复初始颜色
3, 如果我按下向上箭头, 向上移动, 同理还可以向下, 左, 右移动
4, 如果我按下ctrl + 上下左右, 走的步数变大
*/
// 1、
var box = document.getElementById('box')
window.onkeydown = function (e){
e = e || window.event
console.log(e.key)
if(e.ctrlKey && e.key == "c"){
box.style.backgroundColor = `rgba(${Math.floor(Math.random()*256)},${Math.floor(Math.random()*256)},${Math.floor(Math.random()*256)},${(Math.random()).toFixed(1)})`
}else if(e.ctrlKey && e.key == "?" && e.shiftKey){
box.style.backgroundColor = `rgb(${255},${0},${0})`
}else if(e.keyCode == "38"){
// console.log(box.offsetTop)
var value = box.offsetTop - 10
if(e.ctrlKey){
value = box.offsetTop - 30
}
box.style.marginTop = value + "px"
}else if(e.keyCode == "40"){
var value = box.offsetTop + 10
if(e.ctrlKey){
value = box.offsetTop + 30
}
box.style.marginTop = value + "px"
}else if(e.keyCode == "37"){
var value = box.offsetLeft - 10
if(e.ctrlKey){
value = box.offsetLeft - 30
}
box.style.marginLeft = value + "px"
}else if(e.keyCode == "39"){
var value = box.offsetLeft + 10
if(e.ctrlKey){
value = box.offsetLeft + 30
}
box.style.marginLeft = value + "px"
}
}
</script>
</body>
</html>