2016-03-23 4 views
1

Я создал приложение для викторины, которое содержит переключатели, но я хочу, чтобы радиокнопка отображалась по вертикали с ящиками вокруг нее. Я попытался сделать это с помощью CSS, вызвав идентификатор выбора, но он не сработал.Стиль кнопки радио с javascript

Пример того, как я хочу, чтобы это выглядело:

enter image description here

Вместо этого:

enter image description here

var quiz = [{ 
      "question": "What is the full form of IP?", 
      "choices": ["Internet Provider", "Internet Port", "Internet Protocol" , "Other"], 
      "correct": "Other" 
     }, { 
      "question": "Who is the founder of Microsoft?", 
      "choices": ["Bill Gates", "Steve Jobs", "Steve Wozniak" , "Martin Shaba"], 
      "correct": "Bill Gates" 
     }, { 
      "question": "What was your first dream?", 
      "choices": ["8 bits", "64 bits", "1024 bits"], 
      "correct": "8 bits" 
     }, { 
      "question": "The C programming language was developed by?", 
      "choices": ["Brendan Eich", "Dennis Ritchie", "Guido van Rossum"], 
      "correct": "Dennis Ritchie" 
     }, { 
      "question": "What does CC mean in emails?", 
      "choices": ["Carbon Copy", "Creative Commons", "other"], 
      "correct": "Carbon Copy" 
     }]; 


// define elements 
var content = $("content"), 
questionContainer = $("question"), 
choicesContainer = $("choices"), 
scoreContainer = $("score"), 
submitBtn = $("submit"); 

// init vars 
var currentQuestion = 0, 
score = 0, 
askingQuestion = true; 

function $(id) { // shortcut for document.getElementById 
    return document.getElementById(id); 
} 

function askQuestion() { 
    var choices = quiz[currentQuestion].choices, 
    choicesHtml = ""; 

    // loop through choices, and create radio buttons 
    for (var i = 0; i < choices.length; i++) { 
    choicesHtml += "<input type='radio' name='quiz" + currentQuestion + 
    "' id='choice" + (i + 1) + 
    "' value='" + choices[i] + "'>" + 
    " <label for='choice" + (i + 1) + "'>" + choices[i] + "</label><br>"; 
    } 

    // load the question 
    questionContainer.textContent = quiz[currentQuestion].question; 

    // load the choices 
    choicesContainer.innerHTML = choicesHtml; 

    // setup for the first time 
    if (currentQuestion === 0) { 
    scoreContainer.textContent = "0 correct out of " + 
    quiz.length + ""; 
    // submitBtn.textContent = "Submit Answer"; 
    } 

    var radios = document.querySelectorAll('input[type=radio]'); 
    [].forEach.call(radios, function(radio) { 
    radio.onchange = function() { 
     checkAnswer(); 
    } 
    }) 
} 

function checkAnswer() { 
    // are we asking a question, or proceeding to next question? 
    if (askingQuestion) { 
    // submitBtn.textContent = "Next Question"; 
    askingQuestion = false; 

    // determine which radio button they clicked 
    var userpick, 
    correctIndex, 
    radios = document.getElementsByName("quiz" + currentQuestion); 
    for (var i = 0; i < radios.length; i++) { 
     if (radios[i].checked) { // if this radio button is checked 
     userpick = radios[i].value; 
     } 

     // get index of correct answer 
     if (radios[i].value == quiz[currentQuestion].correct) { 
     correctIndex = i; 
     } 
    } 

    // setup if they got it right, or wrong 

    if (userpick == quiz[currentQuestion].correct) { 
     score++; 
    } else { 
    } 

    scoreContainer.textContent = "" + score + " correct out of " + 
    quiz.length + ""; 


    askingQuestion = true; 
    // change button text back to "Submit Answer" 
    //submitBtn.textContent = "Submit Answer"; 
    // if we're not on last question, increase question number 
    if (currentQuestion < quiz.length - 1) { 
     currentQuestion++; 
     askQuestion(); 
    } else { 
     showFinalResults(); 
    } 
    } else { 
    } 
} 

function showFinalResults() { 
    content.innerHTML = "<h1>You did amazing!</h1>" + 
    "<h5>Below are your results</h5>" + 
    "<h2>" + score + " out of " + quiz.length + " questions, " + 
    Math.round(score/quiz.length * 100) + "%<h2>"; 
} 

window.addEventListener("load", askQuestion, false); 
submitBtn.addEventListener("click", checkAnswer, false); 

CSS:

#container { 
    max-width:600px; 
    height: auto; 
    background: #59C1DA; 
    border: 10px solid #333; 
    border-radius: 5px; 
    margin: auto; 
    text-align: center; 
} 

    #content { 
     border: 10px solid #fff; 
     padding: 15px; 
     color: #fff; 
    #question { 
     font-weight: bold; 
    } 
    #score { 
     margin-top: 20px; 
     font-weight: bold; 
    } 

Кнопки не по центру:

enter image description here

ответ

2

Вы можете сделать это s в вашей текущей структуре HTML, используя только CSS. Вот пример:

input[type="radio"] { 
 
    display: none; 
 
} 
 
input[type="radio"] + label { 
 
    border: 5px solid lightblue; 
 
    background-color: lightblue; 
 
    cursor: pointer; 
 
    display: block; 
 
    height: 40px; 
 
    width: 200px; 
 
    text-align: center; 
 
    line-height: 40px; 
 
} 
 
input[type="radio"]:checked + label { 
 
    border: 5px solid blue; 
 
    background-color: dodgerblue; 
 
}
<input id="banana" type='radio' name="quiz" value="banana"> 
 
<label for="banana">Banana</label> 
 
<input id="apple" type='radio' name="quiz" value="apple"> 
 
<label for="apple">Apple</label> 
 
<input id="strawberry" type='radio' name="quiz" value="strawberry"> 
 
<label for="strawberry">Strawberry</label> 
 
<input id="orange" type='radio' name="quiz" value="orange"> 
 
<label for="orange">Orange</label>

+0

PERFECT! Я хочу, чтобы все было сосредоточено, я попробовал добавить «text-align: center», но это не центрировало его !!! – Martin

+0

Он только центрирует текст в поле, но я хочу также центрировать коробки. – Martin

+0

Существует несколько различных вариантов вертикального выравнивания вашего теста. Я взял легкий путь, так как вы знаете высоту окна, и есть только одна строка текста. См. Обновление. – dave

0

нет времени, чтобы написать код, я просто попробую объяснить идею:

создать desidered формы с дивами и текстом, если нет флажка должен существуют и реализовать с помощью JS поведения

на OnClick каждого DIV, изменить класс CSS при добавлении «выбрано», например, или удалить его, если присутствует (это означает, что он был выбран)

Непревзойденное поведение для одного выбора

, чтобы вы могли иметь внешний вид для выбранных элементов.

совет для одного выбора (один выбранный во время): в onClick, если div уже «выбран», удалите этот класс и ничего больше (если вы хотите разрешить режим «без выбора» или ничего не делать «), иначе удалить из всех choicediv„выбранный“класс и добавить его в цель из OnClick

myDiv.onclick = function(e) { 
    if (e.target.classList.contains("selected")) { 
     e.target.classList.remove("selected"); 
    } else { 
     for (var i = 0; i < myChoicedivArray.length; i++) { 
      myChoicedivArray.classList.remove("selected"); 
     } 
     e.target.classList.add("selected"); 
    } 
    //other onclick code here 
} 

отказ от ответственности: я не имею испытания этого кода, это просто, чтобы дать представление

это все. .

+0

Я не совсем понимаю вашу точку зрения, но я думаю, что я в пути. Вы имели в виду вместо того, чтобы создать радио-кнопку через Javascript, я должен был просто поместить его в HTML с помощью тегов div? – Martin

+0

точно, возможно, это просто проще, но это все же обходное решение –

Смежные вопросы