自定义单选按钮选中时如何实现颜色变化?
问题:自定义单选按钮选中时无颜色变化
我是编程新手,正在用HTML和CSS开发一款测验程序(数据来自PostgreSQL,基于Eclipse上的SpringBoot框架,课程不涉及PHP和JQuery)。
遇到的问题:
- 已实现供用户选择的答案列表
- 希望自定义样式的单选按钮在点击选中时改变颜色
- 按钮样式和鼠标悬停光标效果已正常,但选中时颜色无变化
现有代码
HTML代码
<body> <form method="post" action="/result" data-th-object="${form}"> <!-- ヘッダータイトル --> <div class="headerbackground"> <h6>模擬試験オンライン</h6> </div> <br> <!-- 試験指示 --> <div class="examinstruction"> <p>表示された言葉の英単語を以下から選び、</p> <p>OKボタンをクリックしてください。</p> </div> <br> <!-- question --> <div data-th-each="list, st : ${form.list}"> <p style="text-align: center; font-size: 12px;"> <span data-th-text="${list.questionCount}">n</span> <span>/</span> <span data-th-text="${list.questionTotal}">/n</span> </p> <div class="questionborder"> <p style="font-size: 22px; font-weight: bold" data-th-text="${list.content}">question</p> </div> <!-- answer choice --> <fieldset style="border: 0"> <div class="choiceradiobox" data-th-each="choice, stat : ${list.choice}"> <input id="selectedchoice" data-th-name="|choice${st.count}|" type="radio" data-th-value="${choice}" /> <label for="selectedchoice"><span data-th-text="${choice}"></span></label> </div> </fieldset> </div> <!-- 解答完了ボタン --> <div class="submitsection"> <input class="btn btn-secondary" style="font-size: 25px" type="submit" onclick=validate() value="OK!"> </div> </form> </body>
CSS代码
input[type=radio] { display: none; } input[type="radio"]:checked + label { background: #455a64; color: #eceff1; } label { display: block; margin: auto; width: max-content; text-align: center; padding-top : 0.05em; padding-bottom: 0.05em; padding-left: 5em; padding-right: 5em; line-height: 45px; cursor: pointer; border: solid #eceff1; background-color: #eceff1; padding-top: 0.05em; }
问题原因
HTML中id属性必须全局唯一,但你现在所有单选按钮的id都是selectedchoice,对应的label的for属性也都指向这个重复的id。浏览器无法正确关联每个单选按钮和对应的label,导致input[type="radio"]:checked + label这个CSS选择器无法触发样式变化。
解决方法
修改HTML中单选按钮的id和label的for属性,结合Thymeleaf循环的索引生成唯一值:
<div class="choiceradiobox" data-th-each="choice, stat : ${list.choice}"> <!-- 用题目索引和选项索引生成唯一id --> <input id="selectedchoice_${st.count}_${stat.count}" data-th-name="|choice${st.count}|" type="radio" data-th-value="${choice}" /> <!-- label的for属性对应唯一id --> <label for="selectedchoice_${st.count}_${stat.count}"><span data-th-text="${choice}"></span></label> </div>
这样每个单选按钮和对应的label都有唯一的关联,点击选中时,input:checked + label的CSS样式就会正常生效,改变label的背景色和文字颜色。
内容的提问来源于stack exchange,提问作者reinbowpuke
相关产品推荐
相关产品推荐

