在选择答案后寻找一种在问答游戏中禁用按钮(答案)的方法

时间:2021-08-01 15:51:59

标签: javascript html css

我正在寻找一种在选择答案后在问答游戏中禁用按钮(答案)的方法。 我也在寻找一种方法来禁用计数器在选择答案后递增。 还有一个问题是我尝试将 fontawesome.com 和其他网站链接起来使用一个简单的图标,但由于某种原因我只得到空方块。

我不知道为什么我无法使用禁用属性!!帮助你

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Quiz</title>
    <link rel="stylesheet" href="style.css">
    <!-- <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous"> -->
    <!-- you can write script tag like this here -->
    <!-- <script defer src="srcript.js></script>"  (DEFER makes it load after the body) -->
    <script src="https://kit.fontawesome.com/1a0903df7b.js" crossorigin="anonymous"></script>

</head>
<body>
    <!-- container which wraps all content -->
    <div class="container">
        <i class="fas fa-crown"></i>
        <!-- Container to wrap the questions and answers -->
        <!-- class hide to which will be hidden by default-->
        <div id="question-Container" class="hide">
            <!-- div for the Question -->
            <div id="question">Question</div>
            <!-- div block for label and counter p -->
            <div id="block" class="blocks">
                <p id="correctAnswers">Answers: </p> 
                <p id="correctAnswer">0</p>
            </div>
            <!-- <p id="wrongAnswer">0</p> -->
            <!-- Div for Answers -->
            <div id="answer-buttons" class="btn-Grid">
                <button class="btn">Answer 1</button> <!-- "btn correct" -->
                <button class="btn">Answer 2</button> <!-- "btn wrong"-->
                <button class="btn">Answer 3</button>
                <button class="btn">Answer 4</button>
            </div>
        </div>
        <!-- Controls div for start and end -->
        <div class="controls">
            <!-- Shift+Alt+ DownArrow key || Up Arrow key to copy lines of code -->
            <button id="start-btn" class="start-btn btn">Start The Quiz</button>
            <!-- Hide property to keep it hidden -->
            <button id="next-btn" class="next-btn btn hide">Next Question</button>
        </div>
    </div>
    <script src="script.js"></script>
    <!--must call this here or with defer up-->
</body>
</html>
<!-- https://ogkcreative.com/development/8-html-css-tips-for-organizing-code-in-your-web-project/ -->

/* Here I will use border box to create my layout for universal use */
/* learned it from here : https://css-tricks.com/box-sizing/ */
*, *::before, *::after{
    box-sizing: border-box;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 1.5rem;
}
:root{
    --hue-neutral:200;  /*Blue  default*/
    --hue-wrong:0;      /*Red wrong answer*/
    --hue-correct:145;   /*Green correct answer*/
}

body{
    /* Hue  https://www.w3schools.com/colors/colors_hsl.asp
Hue is a degree on the color wheel from 0 to 360. 0 is red, 120 is green, 240 is blue.
Saturation is a percentage value; 0% means a shade of gray and 100% is the full color.
Lightness is also a percentage; 0% is black, 100% is white.
correct syntax hsl(h, s%, l%)

more on hue usage https://stackoverflow.com/questions/65478345/css-variable-calculation-of-hsl-values
we use hue to have more control over all color attributes separately


 how to declare global CSS variables here: https://developer.mozilla.org/en-US/docs/Web/CSS/:root         helped by Teacher Assistant Tariq
*/
    --hue: var(--hue-neutral);
    /* to move everything to the side */
    padding: 0;
    /* to move everything to the side */
    margin: 0;
    display: flex; /* to make it in center of screen */
    width: 100vw;  /*100vw and 100 vh makes it so you take 100% of the view of the width and height */
    height: 100vh;
    justify-content: center; /* to make it in center of screen */
    align-items: center; /* to make it in center of screen */
    background-color: hsl(var(--hue), 100%, 20%);
}

body.correct{
    --hue:var(--hue-correct);
}
body.wrong{
    --hue:var(--hue-wrong);
}
body.neutral{
    --hue: var(--hue-neutral);
}
/*no need to add class neutral since its auto blue default*/

.container{
    width: 800px;
    max-width: 80%; /* we add this to not allow content to overflow*/
    /* height:800px ; */
    /* max-height: 80%; */
    background-color: white;
    border-radius: 10px;
    padding: 10px;
    box-shadow: 0 0 10px 4px ;  /*x offset, y offset, blur, spread how far out it goes*/
}
.blocks{
    display: inline-flex;
     /* grid-template-rows: repeat(2, auto) ; */    
    gap: 10px;
    margin: 20px 0; 
}
.btn-Grid {
    display: grid; /* displays questions undernearth each other in columns*/
    grid-template-columns:repeat(2, auto); /*adds two cloumns for the questions*/
    gap: 10px; /*makes gap between questions*/
    margin: 20px 0; /* we add 20px margin top and bottom 0 left and right*/

}

.btn { /*generic will be applied to all buttons*/
--hue: var(--hue-neutral); /*assining var hue using it here*/
border: 1px solid hsl(var(--hue), 100%, 50%); /*adding border with solid attribute and color and 1px*/
background-color:hsl(var(--hue),100%,50%); /* changing bg color*/
border-radius: 5px; /*rounder radius*/
padding: 5px 10px; /*padding updown 5px leftright 10px*/
color: white;
outline: none;
}

.btn:hover{
    border-color: black; /*just change color of border to blck on mouse hover*/
    transition: 150ms;
    transform:scale(1.03);
}

.btn.correct {                         /*green bg and black color text*/
--hue:var(--hue-correct);
color:black;
}
.btn.wrong{                            /*red bg*/
--hue:var(--hue-wrong);
}

.start-btn{                            /*some css for start btn*/
font-size: 1.5rem;
font-weight: bold;
padding: 10px 30px;
margin:5px;
}

.next-btn{                              /*some css for next btn*/
    font-size: 1.5rem;
    font-weight: bold;
    padding: 10px 30px;
    margin:5px;
}
.controls {   /* corrects start next buttons to be in center*/
    display: flex;
    justify-content: center;
    align-items: center;

}

.hide {  /*hide class will hide everything until we show it with js after we click start*/
display: none;
}
/* Change colors and layout to be nicer!!!!!!!! important*/
/*to do add label css for the score counter*/
/*to do add label css for the timer counter " assuming time left to answer Q is 30 seconds" */
/*to do resize content */
/*add icons*/
/*add sound on correct / on wrong / on finish*/
/*add meaningfull entrypage*/


// I need to make functions for starting game that will display first question and its answers, get next question which displays
// next question and its answers, function for my selected answer
const startButton = document.getElementById("start-btn") //links Variable start button to start-btn button in html
const nextButton = document.getElementById("next-btn") //links Variable start button to start-btn button in html
const questionElementsContainer = document.getElementById("question-Container")  //links this variable to the dev container id which displays question and its answers
const questionElement = document.getElementById("question")
const answerButtonsElement = document.getElementById("answer-buttons")
// 
var cAnswerElement = document.getElementById("correctAnswer")
let wAnswerElement = document.getElementById("worrectAnswer")
let shuffle, currentQuestionsIndex; //undefined 
var cCounter;

startButton.addEventListener("click", startGame)

nextButton.addEventListener("click", () => {
    currentQuestionsIndex++
    // cAnswerElement++
    setNextQuestion()
    // document.getElementById("btn").disabled = false;
})



function startGame() {
    cCounter = 0
    cAnswerElement.innerText=0;
    console.log("GameStarted")

    startButton.classList.add("hide") // hides the button after clicking it
    shuffle = questions.sort(() => Math.random() - 0.5)
    currentQuestionsIndex = 0;
    questionElementsContainer.classList.remove("hide") //unhides question and answers
    setNextQuestion();  // here it will auto put the first question after it started
} //end of startGame function

function setNextQuestion() {
    // setStatusClass(document.body, neutral)
    
    resetState()
    showQuestion(shuffle[currentQuestionsIndex]);
}

function showQuestion(question) {

    questionElement.innerText = question.question

    question.answers.forEach(answer => {
        const button = document.createElement("button")
        button.innerText = answer.text
        button.classList.add("btn")

        if (answer.correct) { //you need to enter correct data
        //   if(answer.correct === true){ cCounter++}
            button.dataset.correct = answer.correct
            // cCounter++
            
        } 
        //  cAnswerElement.innerText= cCounter;
        button.addEventListener('click', selectAnswer)
        
        answerButtonsElement.appendChild(button)

    })

}

//=============================================
function resetState() {
    clearStatusClass(document.body)
    // setStatusClass(document.body, neutral)
    nextButton.classList.add("hide")
    while (answerButtonsElement.firstChild) {
        answerButtonsElement.removeChild(answerButtonsElement.firstChild)
    }
}

//============================================
function selectAnswer(e) {
    const selectedButton = e.target
    const correct = selectedButton.dataset.correct
    setStatusClass(document.body, correct)

    //stack overflow help :D .... I dont understand it fully
    Array.from(answerButtonsElement.children).forEach(button => {
        setStatusClass(button, button.dataset.correct)
        
        //add two buttons with the a appended value from the array
          
    })
    if (shuffle.length > currentQuestionsIndex + 1) {
        nextButton.classList.remove("hide")
        // cAnswerElement.innerText=cAnswerElementt;
        // wAnswerElement.innerText=wAnswerElementt;
    } else {
        startButton.innerText = "Restart The Quiz"
        startButton.classList.remove("hide")
    }

}

function setStatusClass(element, correct) {
    clearStatusClass(element)
    if (correct) {
            cCounter= cCounter+1;
            cAnswerElement.innerText= cCounter;
            //  document.getElementById("btn").disabled = true;          /////////////////////////////////////////////////
        element.classList.add("correct")
        // document.getElementById("btn").disabled = true;
       
    }
    else {
        element.classList.add("wrong")
        cCounter= cCounter-1;
        // document.getElementById("btn").disabled = true;
        // document.getElementById("btn").disabled = true;
    }
}



function clearStatusClass(element) {
    element.classList.remove("correct")
    element.classList.remove("wrong")
}

const questions = [

    {
        question: "What is my name?",
        answers: [
            { text: "Banana", notcorrect: false },
            { text: "Adam", correct: true }
        ]
    },

    {
        question: "What is 2+2?",
        answers: [
            { text: "5", notcorrect: false },
            { text: "4", correct: true }
        ]
    },

    {
        question: "What is the best programming langauge?",
        answers: [
            { text: "JS", notcorrect: false },
            { text: "Java", correct: true }
        ]
    },

    {
        question: "How to copy a line of code in JS?",
        answers: [
            { text: "Ctrl+Alt+Delete", notcorrect: false },
            { text: "Alt + Shift + ArrowKeys", correct: true }
        ]
    },

    {
        question: "Why is CSS so annoying?",
        answers: [
            { text: "Heek", notcorrect: false },
            { text: "It is not!", correct: true }
        ]
    },

    {
        question: "What is my cats name ?",
        answers: [
            { text: "Kitten", notcorrect: false },
            { text: "Jack", correct: true }
        ]
    }
]


// add counter for correct answer
// add counter for wrong answer
// add result
// display above in a nice page where you enter your name
// save in local storage

1 个答案:

答案 0 :(得分:0)

  1. 所有设置禁用属性的行都用“//”注释掉。

  2. 所有设置禁用属性的行都尝试加载元素“btn”,但 ID 字符串需要匹配您要禁用的实际元素,例如“开始-btn”。

  3. 要更改诸如禁用计数器之类的行为,请将增加计数器的代码包装在 if (ShouldCount) { [此处增加的代码] } 条件中。当发生需要停止计数器的事情时,将 ShouldCount 设置为 true 并将其设置为 false;当发生需要重新启动计数器的事情时,将其设置为 true。

  4. 我不知道您想用 FontAwesome 做什么,但您应该提出个别问题,而不是在一个问题中提出所有问题。