ボタンをHTMLコードから押されたときにJavaScriptを実行?

ロジクール炎:

私は、Javaスクリプトでゲームを書くが、問題は、私はHTMLページからゲームを起動したとき、それは直接ゲームを開始することです。私は、スタートボタンが押されたときにゲームを開始し、停止ボタンが押されたときにゲームを停止する必要があります。ボタンが利用可能であるが、彼らはスタートを実行し、正常に動作しているaction.Theゲームを停止するが、私は私のHTMLコードでこれらの2メカニズムを達成する方法はないのですか?

1)[スタート]ゲームスタートボタンが押されたとき?

2)停止ボタンが押されると、ストップゲームは?

私のjavascriptのコード:

    // 'notes' to store Arrows  


var notes = [];


// ==== CLASS FOR ARROWS ==== //

// 1. Direction of arrows
// 2. jQuery img that links to direction bottom
// 3. Destroy when it arrow gets to the 
// 4. Explode when arrow gets to the bottom

// Class Arrow
function Arrow(direction) {

    // CSS spacings for the arrows //
    var xPos = null;

    switch(direction) {

        case "left" : xPos = "350px";
        break;

        case "up" : xPos = "420px";
        break;

        case "down" : xPos = "490px";
        break;

        case "right" : xPos = "560px";
        break;

    }

    this.direction = direction;
    this.image = $("<img src='./arrows/" + direction + ".gif'/>");
    this.image.css({

        position: "absolute",
        top: "0px",
        left: xPos

    });

    $('.stage').append(this.image);

}// ends CLASS Arrow

// To enable animating the arrows
Arrow.prototype.step = function() {

    // Controls the speed of the arrows
    this.image.css("top", "+=4px");

};

// Deletes arrows when they get to bottom of page
Arrow.prototype.destroy = function() {

    // removes the image of the DOM
    this.image.remove();

    // Removes the note/arrow from memory/array
    notes.splice(0,1);

};

// Explodes arrow when hit
Arrow.prototype.explode = function() {

    this.image.remove();

};



// For random arrows
var randNum = 0;

// Frame increasing
var frame = 0;

// Determines the speed of notes
var arrowSpawnRate = 40;


// Random generator for arrows
function randomGen() {

    // Randomizes between 1 and 4
    randNum = Math.floor(Math.random() * 4) + 1;

    if (randNum === 1) {

        notes.push(new Arrow("left"));

    }
    if (randNum === 2) {

        notes.push(new Arrow("right"));

    }
    if (randNum === 3) {

        notes.push(new Arrow("up"));

    }
    if (randNum === 4) {

        notes.push(new Arrow("down"));

    }

}// ends randomGen()


// Render function //
function render() {

    if (frame++ % arrowSpawnRate === 0) {

        randomGen();

    }

    // Animate arrows showering down //
    for (var i = notes.length - 1; i >= 0; i--) {

        notes[i].step();

        // Check for cleanup
        if (notes[i].image.position().top > 615) {

            notes[i].destroy();

        }

    }

}// ends render()



// jQuery to animate arrows //
$(document).ready(function () {

    // shim layer with setTimeout fallback
    window.requestAnimFrame = (function() {

        return window.requestAnimationFrame ||

        window.webkitRequestAnimationFrame ||

        window.mozRequestAnimationFrame ||

        function(callback) {

            window.setTimeout(callback, 40 / 75);

        };

    })();

    /*  place the rAF *before* the render() 
        to assure as close to 60fps with the 
        setTimeout fallback.                    */

    // Infinte loop for game play
    (function animloop() {

        requestAnimFrame(animloop);

        render();

    })();// ends (function animloop() )


});// ends $(doc).ready



// Listening for when the key is pressed
$(document).keydown( function(event) {

    for (var i = 0; i < notes.length; i++) {

            console.log(notes[i].image.position().top);

        if (event.keyCode == 37 && notes[i].direction == "left") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("LEFT! "+notes[i].explode());

            }

        }
        if (event.keyCode == 38 && notes[i].direction == "up") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("UP! "+notes[i].explode());

            }

        }
        if (event.keyCode == 40 && notes[i].direction == "down") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("DOWN! "+notes[i].explode());

            }

        }
        if (event.keyCode == 39 && notes[i].direction == "right") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("RIGHT! "+notes[i].explode());

            }

        }

    }// ends loop

});// ends $(doc).keyup

HTMLコード:

<html>
<head>
    <link rel="icon" href="./arrows/clubbackground.jpg" type="image/gif" sizes="16x16">
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="jsRev.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <title>DDR-Project 1</title>
</head>
<body>
    <div id="BackgroundScene">
        <div id="DanceScoreboard">
            <div id="GameStopped"><button id="StartBtn" class="btnStyle">Begin Game</button>
                <br><br><br><div class="Status">Click Begin Game to start</div>
            </div>
            <div id="GameRunning"><button id="StopBtn" class="btnStyle">Stop Game</button>
                <div id="Status" class="Status"></div>
            </div>
            <div id="dancePoints" class="Points">Points Earned: <div class="OutputText" id="CorrectCount">0</div>
            </div>
        </div>
        <div class="stage"></div> <!-- ENDS .STAGE -->
        <div id="controls">
            <img id="left" src="./arrows/staticLeft.png">
            <img id="up" src="./arrows/staticUp.png">
            <img id="down" src="./arrows/staticDown.png">
            <img id="right" src="./arrows/staticRight.png">
        </div> <!-- ENDS #CONTROLS -->

</body>
</html>

HTMLの画像:

[![ここに画像の説明を入力] [1] [1]

矢印が始まるゲームのボタンを押さずに下って来るのを開始しますか?

// 'notes' to store Arrows  


var notes = [];

let isStarted = false;
// ==== CLASS FOR ARROWS ==== //

// 1. Direction of arrows
// 2. jQuery img that links to direction bottom
// 3. Destroy when it arrow gets to the 
// 4. Explode when arrow gets to the bottom

// Class Arrow
function Arrow(direction) {

    // CSS spacings for the arrows //
    var xPos = null;

    switch(direction) {

        case "left" : xPos = "350px";
        break;

        case "up" : xPos = "420px";
        break;

        case "down" : xPos = "490px";
        break;

        case "right" : xPos = "560px";
        break;

    }

    this.direction = direction;
    this.image = $("<img src='./arrows/" + direction + ".gif'/>");
    this.image.css({

        position: "absolute",
        top: "0px",
        left: xPos

    });

    $('.stage').append(this.image);

}// ends CLASS Arrow

// To enable animating the arrows
Arrow.prototype.step = function() {

    // Controls the speed of the arrows
    this.image.css("top", "+=4px");

};

// Deletes arrows when they get to bottom of page
Arrow.prototype.destroy = function() {

    // removes the image of the DOM
    this.image.remove();

    // Removes the note/arrow from memory/array
    notes.splice(0,1);

};

// Explodes arrow when hit
Arrow.prototype.explode = function() {

    this.image.remove();

};



// For random arrows
var randNum = 0;

// Frame increasing
var frame = 0;

// Determines the speed of notes
var arrowSpawnRate = 40;


// Random generator for arrows
function randomGen() {

    // Randomizes between 1 and 4
    randNum = Math.floor(Math.random() * 4) + 1;

    if (randNum === 1) {

        notes.push(new Arrow("left"));

    }
    if (randNum === 2) {

        notes.push(new Arrow("right"));

    }
    if (randNum === 3) {

        notes.push(new Arrow("up"));

    }
    if (randNum === 4) {

        notes.push(new Arrow("down"));

    }

}// ends randomGen()


// Render function //
function render() {

    if (frame++ % arrowSpawnRate === 0) {

        randomGen();

    }

    // Animate arrows showering down //
    for (var i = notes.length - 1; i >= 0; i--) {

        notes[i].step();

        // Check for cleanup
        if (notes[i].image.position().top > 615) {

            notes[i].destroy();

        }

    }

}// ends render()



// jQuery to animate arrows //
$(document).ready(function () {

    // shim layer with setTimeout fallback
    window.requestAnimFrame = (function() {

        return window.requestAnimationFrame ||

        window.webkitRequestAnimationFrame ||

        window.mozRequestAnimationFrame ||

        function(callback) {

            window.setTimeout(callback, 40 / 75);

        };

    })();

    /*  place the rAF *before* the render() 
        to assure as close to 60fps with the 
        setTimeout fallback.                    */

    // Infinte loop for game play
    (function animloop() {

        if(requestAnimFrame(animloop));
        // ------------ Change is made here ----------
        if(isStarted){
           render();
        }

    })();// ends (function animloop() )


});// ends $(doc).ready



// Listening for when the key is pressed
$(document).keydown( function(event) {

    for (var i = 0; i < notes.length; i++) {

            console.log(notes[i].image.position().top);

        if (event.keyCode == 37 && notes[i].direction == "left") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("LEFT! "+notes[i].explode());

            }

        }
        if (event.keyCode == 38 && notes[i].direction == "up") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("UP! "+notes[i].explode());

            }

        }
        if (event.keyCode == 40 && notes[i].direction == "down") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("DOWN! "+notes[i].explode());

            }

        }
        if (event.keyCode == 39 && notes[i].direction == "right") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("RIGHT! "+notes[i].explode());

            }

        }

    }// ends loop

});// ends $(doc).keyup

const startButton = document.getElementById('StartBtn');
const stopButton = document.getElementById('StopBtn');

startButton.onclick = function(){
   isStarted = true;
}
stopButton.onclick = function(){
   isStarted = false;
}
.stage {
	width: 1150px;    
	height: 500px;
	margin:0;
	padding:0;
    background-image: url('./arrows/clubbackground.jpg');
    background-repeat: no-repeat;
    background-size: contain;
    position: relative;
	text-align: center;
	opacity: 90%;
	
}

#controls {
	padding-left: 350px;

}
/*#left {

}
#up {

}
#down {

}
#right {

}*/
.btnStyle {
	border-radius: 4px;
	border: medium solid #000000;
	background-color:rgb(92, 250, 246);
	font-family: "Arial", Impact, Charcoal, sans-serif;
	font-weight: bold;
	font-size:20px;
    color: #ffffff;
	padding: 5px 30px;
	margin:8px 70px;
}

#StartBtn{
	position: fixed;
	left: 100px;
    text-shadow: 2px 2px 4px black;
}

#StopBtn{
    position: fixed;
	left: 500px;
	down: 10px;
    border-radius: 4px;
	border: medium solid #000000;
	background-color:rgb(92, 250, 246);
	font-family: "Arial", Impact, Charcoal, sans-serif;
	font-weight: bold;
	font-size:20px;
    color: #ffffff;
    text-shadow: 2px 2px 4px black;
	padding: 5px 30px;
	margin:8px 70px;
}
<html>
<head>
    <link rel="icon" href="./arrows/clubbackground.jpg" type="image/gif" sizes="16x16">
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <script src="jsRev.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
    <title>DDR-Project 1</title>
</head>
<body>
    <div id="BackgroundScene">
        <div id="DanceScoreboard">
            <div id="GameStopped"><button id="StartBtn" class="btnStyle">Begin Game</button>
                <br><br><br><div class="Status">Click Begin Game to start</div>
            </div>
            <div id="GameRunning"><button id="StopBtn" class="btnStyle">Stop Game</button>
                <div id="Status" class="Status"></div>
            </div>
            <div id="dancePoints" class="Points">Points Earned: <div class="OutputText" id="CorrectCount">0</div>
            </div>
        </div>
        <div class="stage"></div> <!-- ENDS .STAGE -->
        <div id="controls">
            <img id="left" src="./arrows/staticLeft.png">
            <img id="up" src="./arrows/staticUp.png">
            <img id="down" src="./arrows/staticDown.png">
            <img id="right" src="./arrows/staticRight.png">
        </div> <!-- ENDS #CONTROLS -->

</body>
</html>

COY:

gameStarted状態を認識するために、あなたのメインのJavaScriptを変更します。

var notes = [];
var gameStarted = false;

...

    (function animloop() {

        if (gameStarted) {

            requestAnimFrame(animloop);

            render();

        } else {

            window.setTimeout(animloop, 1000); // check the state per second

        }

    })();// ends (function animloop() )

開始/終了ボタンで、のような属性を追加します。

<button id="StartBtn" class="btnStyle" onclick="gameStarted=true;">
<button id="StopBtn" class="btnStyle" onclick="gameStarted=false;">

全体のコード:

<html>
<head>
    <link rel="icon" href="./arrows/clubbackground.jpg" type="image/gif" sizes="16x16">
    <script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
    <script src="jsRev.js" type="text/javascript"></script>
    <link rel="stylesheet" type="text/css" href="style.css">
    <title>DDR-Project 1</title>
</head>
<body>
    <div id="BackgroundScene">
        <div id="DanceScoreboard">
            <div id="GameStopped"><button id="StartBtn" class="btnStyle" onclick="gameStarted=true;">Begin Game</button>
                <br><br><br><div class="Status">Click Begin Game to start</div>
            </div>
            <div id="GameRunning"><button id="StopBtn" class="btnStyle" onclick="gameStarted=false;">Stop Game</button>
                <div id="Status" class="Status"></div>
            </div>
            <div id="dancePoints" class="Points">Points Earned: <div class="OutputText" id="CorrectCount">0</div>
            </div>
        </div>
        <div class="stage"></div> <!-- ENDS .STAGE -->
        <div id="controls">
            <img id="left" src="./arrows/staticLeft.png">
            <img id="up" src="./arrows/staticUp.png">
            <img id="down" src="./arrows/staticDown.png">
            <img id="right" src="./arrows/staticRight.png">
        </div> <!-- ENDS #CONTROLS -->

</body>
</html>
// 'notes' to store Arrows  


var notes = [];
var gameStarted = false;


// ==== CLASS FOR ARROWS ==== //

// 1. Direction of arrows
// 2. jQuery img that links to direction bottom
// 3. Destroy when it arrow gets to the 
// 4. Explode when arrow gets to the bottom

// Class Arrow
function Arrow(direction) {

    // CSS spacings for the arrows //
    var xPos = null;

    switch(direction) {

        case "left" : xPos = "350px";
        break;

        case "up" : xPos = "420px";
        break;

        case "down" : xPos = "490px";
        break;

        case "right" : xPos = "560px";
        break;

    }

    this.direction = direction;
    this.image = $("<img src='./arrows/" + direction + ".gif'/>");
    this.image.css({

        position: "absolute",
        top: "0px",
        left: xPos

    });

    $('.stage').append(this.image);

}// ends CLASS Arrow

// To enable animating the arrows
Arrow.prototype.step = function() {

    // Controls the speed of the arrows
    this.image.css("top", "+=4px");

};

// Deletes arrows when they get to bottom of page
Arrow.prototype.destroy = function() {

    // removes the image of the DOM
    this.image.remove();

    // Removes the note/arrow from memory/array
    notes.splice(0,1);

};

// Explodes arrow when hit
Arrow.prototype.explode = function() {

    this.image.remove();

};



// For random arrows
var randNum = 0;

// Frame increasing
var frame = 0;

// Determines the speed of notes
var arrowSpawnRate = 40;


// Random generator for arrows
function randomGen() {

    // Randomizes between 1 and 4
    randNum = Math.floor(Math.random() * 4) + 1;

    if (randNum === 1) {

        notes.push(new Arrow("left"));

    }
    if (randNum === 2) {

        notes.push(new Arrow("right"));

    }
    if (randNum === 3) {

        notes.push(new Arrow("up"));

    }
    if (randNum === 4) {

        notes.push(new Arrow("down"));

    }

}// ends randomGen()


// Render function //
function render() {

    if (frame++ % arrowSpawnRate === 0) {

        randomGen();

    }

    // Animate arrows showering down //
    for (var i = notes.length - 1; i >= 0; i--) {

        notes[i].step();

        // Check for cleanup
        if (notes[i].image.position().top > 615) {

            notes[i].destroy();

        }

    }

}// ends render()



// jQuery to animate arrows //
$(document).ready(function () {

    // shim layer with setTimeout fallback
    window.requestAnimFrame = (function() {

         return window.requestAnimationFrame ||

         window.webkitRequestAnimationFrame ||

         window.mozRequestAnimationFrame ||

         function(callback) {

            window.setTimeout(callback, 40 / 75);

        };

    })();

    /*  place the rAF *before* the render() 
        to assure as close to 60fps with the 
        setTimeout fallback.                    */

    // Infinte loop for game play
    (function animloop() {

        if (gameStarted) {

            requestAnimFrame(animloop);

            render();

        } else {

            window.setTimeout(animloop, 1000); // check the state per second

        }

    })();// ends (function animloop() )


});// ends $(doc).ready



// Listening for when the key is pressed
$(document).keydown( function(event) {

    for (var i = 0; i < notes.length; i++) {

            console.log(notes[i].image.position().top);

        if (event.keyCode == 37 && notes[i].direction == "left") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("LEFT! "+notes[i].explode());

            }

        }
        if (event.keyCode == 38 && notes[i].direction == "up") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("UP! "+notes[i].explode());

            }

        }
        if (event.keyCode == 40 && notes[i].direction == "down") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("DOWN! "+notes[i].explode());

            }

        }
        if (event.keyCode == 39 && notes[i].direction == "right") {

            if (notes[i].image.position().top > 490 && notes[i].image.position().top < 730) {

                console.log("RIGHT! "+notes[i].explode());

            }

        }

    }// ends loop

});// ends $(doc).keyup

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=32674&siteId=1