为什么HTML5会破坏这段代码?

时间:2013-11-21 01:59:12

标签: javascript html css html5

我不确定如何详细询问此问题,但为什么在将文档设置为<!DOCTYPE html>时,此网站无法正常显示?我在多个浏览器(即firefox,chrome,opera)上尝试过这个页面,除非我省略<!DOCTYPE html>,否则它们都显示不正确。这是代码:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>DotSmasher</title>
<link rel="stylesheet" href="dotSmasher.css" type="text/css" />
<script type="text/javascript" src="dotSmasher.js"></script>
</head>
<body onload="setGameAreaBounds()" onresize="setGameAreaBounds()">
<div id="scoreLabel">Score: 0</div>
<div id="pageTitle">DotSmasher</div>
<div id="gameArea">
    <button id="dot" onClick="detectHit()"></button>
    </div>
</body>
</html>

以下是它的外观截图: http://i.stack.imgur.com/TNTrQ.jpg

以下是<!DOCTYPE html>照片的截图: http://i.stack.imgur.com/r5Qtm.jpg

javascript和CSS代码如下:

var score = 0;
var aWidth;
var aHeight;
var timer;
function detectHit() {
score += 1;
scoreLabel.innerHTML = "Score: " + score;
}
function setGameAreaBounds() {
if (document.all) {
    aWidth = document.body.clientWidth;
    aHeight = document.body.clientHeight;
}
else {
    aWidth = innerWidth;
    aHeight = innerHeight;
}
aWidth -= 30;
aHeight -= 95;
document.getElementById("gameArea").style.width = aWidth;
document.getElementById("gameArea").style.height = aHeight;
aWidth -= 74;
aHeight -= 74;
moveDot();

}
function moveDot() {
var x = Math.floor(Math.random() * aWidth);
var y = Math.floor(Math.random() * aHeight);
if (x < 10)
    x = 10;
if (y < 10)
    y = 10;
document.getElementById("dot").style.left = x;
document.getElementById("dot").style.top = y;
clearTimeout(timer);
timer = setTimeout("moveDot()", 1000);
}


#scoreLabel {
font-family: Arial, Helvetica, sans-serif;
font-size: 14pt;
color: #000000;
font-weight: bold;
position: absolute;
top: 10px;
height: 25px;
}

#pageTitle {
font-family: Arial, Helvetica, sans-serif;
font-size: 24pt;
font-weight: bold;
color: #000099;
position: absolute;
top: 35px;
left: 10px;
height: 25px;
}

#gameArea {
position: absolute;
top: 75px;
left: 10px;
border: 1px solid #000000;
}

#dot {
position: absolute;
top: 25px;
left: 25px;
background-color: #000099;
width: 64px;
height: 64px;
}

#stop {
position: absolute;
top: 50px;
}

1 个答案:

答案 0 :(得分:2)

问题是你从大学书中得到的代码是错误的。我发现这本书是here

目前至少有两件事是错的。

var x = Math.floor(Math.random() * aWidth);
var y = Math.floor(Math.random() * aHeight);

aWidthaHeight都未初始化,因此您将乘以NULL。将它们设置为1.像这样:

var aWidth = 1;
var aHeight = 1;

另外,

document.getElementById("dot").style.left = x;
document.getElementById("dot").style.top = y;

应该是:

document.getElementById("dot").style.left = x + "px";
document.getElementById("dot").style.top = y + "px";

他们错过了位置末尾的“px”。

由于浏览器的怪癖模式,RobG是正确的,没有DOCTYPE html

希望这有帮助。