通过仅使用JS/ html,我希望检测是否按下了空格键,当按下空格键时,我希望将html更改为另一个文件。(注意,我只是在使用localhost,所以我想从localhost:1337转到localhost:1337/mainmenu)
这就是我所拥有的,但似乎有一个潜在的问题。我有一个index.html文件和一个index.js文件。我的js文件中有一个允许文本淡入淡出的脚本。这个脚本运行得很好。然而,当我为我的键盘事件添加脚本时,第一个脚本似乎停止工作。
有人能指出这两个脚本是否相互干扰吗?另外,有人能解释一下为什么我的键盘脚本不能运行吗?
JS:
var speed = 1000;
var t = setInterval(function(){
var slideSource = document.getElementById('play');
slideSource.classList.toggle('fade');
}, speed);
//SEPERATE SCRIPTS
window.addEventListener("keydown", pressToPlay, false);
function checkSpacebar(e) {
if(e.keyCode == "32") {
window.location.href = "localhost:1337/mainmenu";
}
}
HTML:
<html>
<body>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<div class="container">
<img src="images/image.jpg" alt="Loading Image.." style="width:100%;height:100%;">
<div class="title">
<img src = "images/redfox.png" style = "width:7%">
Oregon Trail:Marist Edition
<div class = "marist"><img src = "images/marist.png" style = "width:15%"></div>
<img src = "images/redfox.png" style = "width:7%"></div>
<div id ="play">Press Spacebar To Play!</div>
</div>
<link rel="stylesheet" type="text/css" href="/css/index.css">
<script src="/JS/index.js" type="text/javascript"></script>
</body>
</html>
发布于 2018-09-27 05:53:22
//SEPERATE SCRIPTS
window.addEventListener("keydown", checkSpaceBar, false);
function checkSpaceBar(e) {
if(e.keyCode == "32") {
window.location.href = "localhost:1337/mainmenu";
}
}
缩小的ES6样式
window.addEventListener("keydown",(e) => {if(e.keyCode === 32) window.location.href="localhost:1337/mainmenu";}, false);
发布于 2018-09-27 06:05:54
您的JavaScript
代码中有一些错误,您正在向keydown事件侦听器传递一个未定义的变量(实际上是一个回调函数),并且您以"
开始一个字符串,并使用'
结束它,这将生成一个意外的令牌错误,因此您的代码将崩溃,因此您应该使用"
或'
,而不是同时使用这两者。
以下是经过必要修改的代码:
// your passing an undefined pressToPlay function instead of checkSpacebar
window.addEventListener("keydown", checkSpacebar, false);
function checkSpacebar(e) {
// use "32" or '32' and as of the keyCode attribute is an integer then no need to use 32 as a string, I mean instead of "32" write just 32.
if(e.keyCode == 32) {
window.location.href = "localhost:1337/mainmenu";
}
}
希望我让你走得更远了。
发布于 2018-09-27 06:59:19
在URL前添加Http。
window.addEventListener("keydown", checkSpaceBar, false);
function checkSpaceBar(e) {
if(e.keyCode == "32") {
window.open('http://localhost:1337/mainmenu',"_self");
}
}
https://stackoverflow.com/questions/52526432
复制相似问题