一、鼠标拖拽方块
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Div跟随鼠标移动</title>
<style type="text/css">
#box1{
width: 200px;
height: 200px;
background-color: darksalmon;
border: #000000 solid 2px;
text-align: center;
line-height: 200px;
position: absolute;//开启定位
}
#box2{
width: 500px;
height: 500px;
background-color: cadetblue;
text-align: center;
line-height: 500px;
font-size:50px;
}
</style>
<script type="text/javascript">
window.onload=function(){
/*
实现DIV跟着鼠标移动
*/
var box1=document.getElementById("box1");
document.onmousemove=function(event){
//获取鼠标的坐标
var left=event.pageX;
var top=event.pageY;
//设置DIV的偏移量,设置position才能用
box1.style.left=left+"px";
box1.style.top=top+"px";
};
/* 设置了这个则box1在跟随鼠标移动时不会移动进box2 */
var box2=document.getElementById("box2");
box2.onmousemove=function(event){
event.cancelBubble=true;
};
};
</script>
</head>
<body>
<div id="box1" >鼠标大哥!我跟你走!</div>
<div id="box2">你不要过来啊!</div>
</body>
</html>
二、盒子根据键盘的上下左右按钮移动
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
#box1{
width: 600px;
height: 600px;
border: #000000 solid 1px;
background-image: url(img/4.jpg);
position: absolute;
}
</style>
<script type="text/javascript">
/*
使div可以根据不同的方向键向不同的方向移动
37 左 38上 39右 40下
*/
window.onload=function(){
document.onkeydown=function(event){
event=event||window.event;
//定义变量表示速度
var spead=20;
//当用户按了ctrl时速度加快
if(event.ctrlKey){
spead=100;
}
switch(event.keyCode){
case 37:
box1.style.left=box1.offsetLeft-spead+"px";
break;
case 38:
box1.style.top=box1.offsetTop-spead+"px";
break;
case 39:
box1.style.left=box1.offsetLeft+spead+"px";
break;
case 40:
box1.style.top=box1.offsetTop+spead+"px";
break;
}
};
};
</script>
</head>
<body>
<div id="box1"></div>
</body>
</html>
以上两个小练习运用的均是前几期的知识,若有疑问可以回顾前几期知识点