【发布时间】:2021-09-15 13:54:58
【问题描述】:
所以我正在尝试制作一个考试页面。我可以选择复选框。选择选择时,我希望其背景要改变。但我遇到了一些问题。
你可以看到代码和屏幕here
下面是 HTML 代码:
<div class="questions">
<div class="questions-left-column">
<div class="question-area">
<p>QUESTION</p>
<div class="choices">
<div class="choice answer" id="1answer">
<input id="choice-1a" type="radio" name="radio1" />
<label for="choice-1a">
<strong>A.</strong>
Option A
</label>
</div>
<div class="choice">
<input id="choice-1b" type="radio" name="radio1" />
<label for="choice-1b">
<strong>B.</strong>
Option B
</label>
</div>
<div class="choice">
<input id="choice-1c" type="radio" name="radio1" />
<label for="choice-1c">
<strong>C.</strong>
Option C
</label>
</div>
<div class="choice">
<input id="choice-1d" type="radio" name="radio1" />
<label for="choice-1d">
<strong>D.</strong>
Option D
</label>
</div>
<div class="choice">
<input id="choice-1e" type="radio" name="radio1" />
<label for="choice-1e">
<strong>E.</strong>
Option E
</label>
</div>
</div>
<div class="show-answer-button-container">
<label class="show-answer">
<fieldset hidden class="answers">
<strong>Correct Answer: </strong>
A
</fieldset>
<button type="button" onclick="checkAnswers()">Check Answers</button>
</label>
</div>
</div>
</div>
</div>
下面是 CSS 代码:
.selectt {
display: none;
}
.questions {
display: flex;
justify-content: center;
border: 0.3px solid gray;
padding: 10px;
}
.questions-left-column {
flex-direction: column;
border-right: 1px solid black;
width: 400px;
padding-right: 100px;
}
.question-area {
margin-bottom: 30px;
border: 0.3px solid gray;
padding: 10px;
}
.choice {
width: 350px;
padding: 0.5rem;
align-content: left;
justify-self: center;
border: 1px solid darkgrey;
}
.choice input[type="radio"]:checked + label {
padding: 0.5rem;
background: rgb(226, 182, 182);
cursor: default;
}
input {
visibility: hidden;
}
label {
cursor: pointer;
}
.show-answer-button-container {
margin: 10px;
}
.show-answer {
margin-top: 0.5rem;
align-items: right;
padding: 0.1rem;
border: 0.5px solid rgb(119, 108, 108);
background: rgb(133, 183, 212);
color: white;
border-radius: 0.2rem;
}
下面是JS代码:
function checkAnswers() {
var elements = document.getElementsByClassName("choice answer");
for (var i = 0; i < elements.length; i++) {
elements[i].style.backgroundColor = "lightgreen";
}
}
这是我的问题:
-
When a choice is selected, only background of text is changing.整个选项框的背景应该会改变。
-
单击“显示答案”按钮时。正确答案以绿色背景显示,但如果选择的选项与答案文本的背景相同,则背景为紫色,框的背景为绿色。
感谢您的帮助!
【问题讨论】:
-
“整个选项框的背景应该改变。” - 你目前只是改变标签的背景。而且您不能仅通过 CSS 更改父容器,因为 CSS 无法在 DOM 中向上选择。所以如果你想完全用 CSS 来完成这部分 - 那么你需要注意标签元素覆盖整个盒子。
-
我该怎么做?我不必使用 CSS。
-
为单选按钮添加
position:absolute,使它们脱离正常的布局流程。然后从.choice中删除填充,并将其放在label元素上 - 并将display:block添加到它们。 -
感谢您的成功。但是现在当点击显示答案按钮时,如果选择的选项正确,背景不会变成绿色?
-
它正在变成绿色 - 但它是 div 元素的背景,现在它完全被标签覆盖,并且有它的自己的背景。所以改为设置标签的背景。
标签: javascript html css frontend