我只是在这里复制我的所有代码:
HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Follow cursor</title>
<script type="text/javascript" src="script.js"></script>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">
</head>
<body onmousemove="follow(event)">
<div id="box"></div>
<div id="top-left" class="mainn"></div>
<div id="top-right" class="mainn"></div>
<div id="lower-left" class="mainn"></div>
<div id="lower-right" class="mainn"></div>
</body>
CSS
*{
margin: 0px;
padding: 0px;
}
html, body{
height: 100%;
}
div.mainn{
width: 50%;
height: 50%;
float: left;
position: static;
}
#top-left, #lower-right{
background-color: #e3e3e3;
}
#top-right, #lower-left{
background-color: #d1d1d1;
}
#box{
width: 46px;
height: 46px;
border: 2px solid #437325;
background-color: #98C77B;
position: absolute;
}
JS
function follow(e){
var bx = document.getElementById("box");
var mouseX = e.pageX;
var mouseY = e.pageY;
var screenX = window.innerWidth;
var screenY = window.innerHeight;
if((mouseX < (screenX / 2)) && (mouseY < (screenY / 2))){
bx.style.left = e.pageX + 20;
bx.style.top = e.pageY + 20;
}
else if((mouseX > (screenX / 2)) && (mouseY < (screenY / 2))){
bx.style.left = e.pageX - 70;
bx.style.top = e.pageY + 20;
}
else if((mouseX < (screenX / 2)) && (mouseY > (screenY / 2))){
bx.style.left = e.pageX + 20;
bx.style.top = e.pageY - 70;
}
else if((mouseX > (screenX / 2)) && (mouseY > (screenY / 2))){
bx.style.left = e.pageX - 70;
bx.style.top = e.pageY - 70;
}
}
现在这个代码在这种状态下完美运行,有4个div作为视觉背景,并且在光标之后有一个小的50x50px对象,取决于光标位于屏幕的四分之一处。
当我在HTML的开头使用<!DOCTYPE html>
时,问题就出现了。 4个50%宽50%高的div不再显示,50x50px对象卡在左上角。
我猜测盒子div试图跟随我的光标,但另外4&#34;视觉&#34; divs在角落里坚持下去,所以我试着评论那些,但我得到了相同的结果。
答案 0 :(得分:1)
CSS长度(0除外)需要单位。
bx.style.left = e.pageX + 20;
您没有指定要分配的值的单位。