为什么我的Javascript内容在网页中不可见



我是javascript的新手。我试图使用html,css和JS制作一些测验游戏。 在测验中,我想要 1 分钟的计时器。我为计时器和模板编写了单独的代码。计时器工作正常。

但是当我合并两个代码计时器时,不可见。虽然在 1 分钟完成后它会给出消息"时间到了"。我使用了定位属性并尝试了不同的位置,但仍然不可见。

<html>
<head>
<style>
.score
{
position:absolute;
left:900;
}
#whole
{
background-color:black;
color:white;
width:80%;
height:70%;
position:relative;
top:45;
left:95;
border:4px solid black;
}
.optns
{
width:40%;
height:5%
}
#question
{
color:black;
background-color:#f2f2f2;
width:99%;
height:20%;
position:absolute;
top:35;
left:5;
}
.optn1
{
position:absolute;
top:190;
left:120;
}
.optn2
{
position:absolute;
top:230;
left:120;
}
.optn3
{
position:absolute;
top:270;
left:120;
}
.optn4
{
position:absolute;
top:310;
left:120;
}
.prev
{
position:absolute;
down:80px;
left:200px;
}
.next
{
position:absolute;
down:80px;
right:200px;
}
#timer
{
position:absolute;
top:1000px;
background-color:pink;
color:blue;
font-family:cursive;
z-index:9999;
}
</style>
</head>
<body>
<div id=whole>
<center>TIMER HERE</center>
<script>
var fixed=new Date();
var fixedsecond=fixed.getSeconds();
var fixedmin=fixed.getMinutes();
function changetime()
{
var current=new Date();
var currentsecond=current.getSeconds();
var currentmin=current.getMinutes();
var m=currentmin-fixedmin;
var s=(currentsecond-fixedsecond);
if(s<0)
{
s=s+60
m=m-1;
}
if(m>=1)
{
clearInterval(t);
prompt("TIME IS UP");
}
document.getElementById("timer").innerHTML="<center id=timer><h1>"+m+":"+s
+"</center></h1>";
}
var t=setInterval(changetime,1000);
</script>
<span class="score">SCORE</span>
<div id=question>
Question here
</div>
</div>
<button class="optn1 optns">OPTION 1</button>
<button class="optn2 optns">OPTION 2</button>
<button class="optn3 optns">OPTION 3 </button>
<button class="optn4 optns">OPTION 4</button>
<button class=prev>PREVIOUS</button>
<button class="next">NEXT</button>
</body>
</html>

提前感谢!

你调用document.getElementById("timer")但这个元素在HTML中还不存在。你需要在HTML中拥有这个元素,或者通过JavaScript在文档中创建它。

尝试这样的事情:

<div id="timer">TIMER HERE</center>

和JS:

document.getElementById("timer").innerHTML = m + ":" + s;

另外 - 您不应该使用<center>,因为它已被弃用。

1( 更改

<center id="timer">TIMER HERE</center>

有了这个:

<div id="timer">TIMER HERE</div>

2(您还需要更改此设置:

document.getElementById("timer").innerHTML = "<center id=timer><h1>" + m + ":" + s

有了这个:

document.getElementById("timer").innerHTML=m+":"+s;

3(你的CSS被窃听,更改:

#timer {
position: absolute;
top: 1000px;
background-color: pink;
color: blue;
font-family: cursive;
z-index: 9999;
}

有了那个:

#timer
{
text-align: center;
background-color:pink;
color:fff;
font-family:cursive;
}

现在您可以看到您的计时器...

您应该直接从使用任何浏览器(Safari,Chrome等(的Web开发人员控制台看到javascript错误。 此代码在此行失败

document.getElementById("timer").innerHTML

没有 id "timer" 的元素。

你在HTML中使用"whole"作为id,但在javascript中使用"timer"id。

更新脚本中的 id,如下所示:

document.getElementById("timer").innerHTML

document.getElementById("whole").innerHTML

最新更新