У меня есть группа переключателей и кнопка отправки. Когда я нажимаю кнопку «Отправить», появляется сообщение о том, на какую радио-кнопку я нажал. Что я хочу сделать сейчас, это изменить цвет выбранной радиокнопки, как я могу это сделать? Я перепробовал много вещей без успеха. Вот код
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
}
}
}
<input type="radio" name="gender" class="one" value="Male" />Male <br>
<input type="radio" name="gender" class="one" value="Female" />Female<br>
<input type="radio" name="gender" class="one" value="Other" />Other<br>
<div id="display"> </div>
<button onclick="selectedButton()">Submit</button>
4 ответа
Вы можете обернуть переключатели в div
, а затем применить класс CSS при выборе. Затем в вашем CSS вы можете определить необходимые стили.
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
optionContainer[i].parentElement.classList.add('selected');
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
} else {
optionContainer[i].parentElement.classList.remove('selected');
}
}
}
.selected {
color: Red;
}
<div>
<input type="radio" name="gender" class="one" value="Male" />Male
</div>
<div>
<input type="radio" name="gender" class="one" value="Female" />Female
</div>
<div>
<input type="radio" name="gender" class="one" value="Other" />Other
</div>
<div id="display"> </div>
<button onclick="selectedButton()">Submit</button>
Вы можете настроить стиль кнопки радио по вашему желанию. Прямое моделирование на радио не будет работать.
Ниже приведен пример.
Вы также не указали стиль для класса selected
. Пожалуйста, добавьте это, чтобы увидеть изменение стиля.
Это стиль, который вам нужен.
.container.selected input:checked ~ .checkmark {
background-color: red;
}
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
optionContainer[i].parentElement.classList.add("selected");
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
} else {
optionContainer[i].parentElement.classList.remove("selected");
}
}
}
/* The container */
.container {
display: block;
position: relative;
padding-left: 35px;
margin-bottom: 12px;
cursor: pointer;
font-size: 22px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
/* Hide the browser's default radio button */
.container input {
position: absolute;
opacity: 0;
cursor: pointer;
}
/* Create a custom radio button */
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 25px;
width: 25px;
background-color: #eee;
border-radius: 50%;
}
/* On mouse-over, add a grey background color */
.container:hover input ~ .checkmark {
background-color: #ccc;
}
/* When the radio button is checked, add a blue background */
.container input:checked ~ .checkmark {
background-color: #2196f3;
}
/* Create the indicator (the dot/circle - hidden when not checked) */
.checkmark:after {
content: "";
position: absolute;
display: none;
}
/* Show the indicator (dot/circle) when checked */
.container input:checked ~ .checkmark:after {
display: block;
}
/* Style the indicator (dot/circle) */
.container .checkmark:after {
top: 9px;
left: 9px;
width: 8px;
height: 8px;
border-radius: 50%;
background: white;
}
.container.selected input:checked ~ .checkmark {
background-color: red;
}
<h1>Custom Radio Buttons</h1>
<label class="container"
>One
<input type="radio" class="one" checked="checked" name="radio" value="One" />
<span class="checkmark"></span>
</label>
<label class="container"
>Two
<input type="radio" class="one" name="radio" value="Two" />
<span class="checkmark"></span>
</label>
<label class="container"
>Three
<input type="radio" name="radio" class="one" value="Three" />
<span class="checkmark"></span>
</label>
<label class="container"
>Four
<input type="radio" class="one" name="radio" value="Four" />
<span class="checkmark"></span>
</label>
<div id="display"></div>
<button onclick="selectedButton()">Submit</button>
Вы можете заключить весь элемент ввода в диапазон и с помощью parentNode
изменить цвет полной кнопки-переключателя.
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
optionContainer[i].style.backgroundColor = "blue";
optionContainer[i].parentNode.style.backgroundColor = "blue";
optionContainer[i].parentNode.style.color = "yellow"
} else {
optionContainer[i].style.backgroundColor = "";
optionContainer[i].parentNode.style.backgroundColor = "";
optionContainer[i].parentNode.style.color = ""
}
}
}
<span><input type="radio" name="gender" class="one" value="Male" />Male</span> <br>
<span><input type="radio" name="gender" class="one" value="Female" />Female</span><br>
<span><input type="radio" name="gender" class="one" value="Other" />Other</span><br>
<div id="display"> </div>
<button onclick="selectedButton()">Submit</button>
Вы можете заключить метки в промежуток и, используя nextSibling
раскрасить их переключателем
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
optionContainer[i].style.backgroundColor = "blue";
optionContainer[i].nextSibling.style.backgroundColor = "blue";
optionContainer[i].nextSibling.style.color = "yellow"
} else {
optionContainer[i].style.backgroundColor = "";
optionContainer[i].nextSibling.style.backgroundColor = "";
optionContainer[i].nextSibling.style.color = ""
}
}
}
<input type="radio" name="gender" class="one" value="Male" /><span>Male</span> <br>
<input type="radio" name="gender" class="one" value="Female" /><span>Female</span><br>
<input type="radio" name="gender" class="one" value="Other" /><span>Other</span><br>
<div id="display"> </div>
<button onclick="selectedButton()">Submit</button>
function selectedButton() {
const optionContainer = document.querySelectorAll(".one");
for (var i = 0; i < optionContainer.length; i++) {
if (optionContainer[i].checked) {
document.getElementById("display").innerHTML = "You have selected: " + optionContainer[i].value;
optionContainer[i].style.backgroundColor = "red";
}
else {
optionContainer[i].style.backgroundColor = "";
}
}
}
Похожие вопросы
Новые вопросы
javascript
По вопросам программирования на ECMAScript (JavaScript/JS) и его различных диалектах/реализациях (кроме ActionScript). Обратите внимание, что JavaScript — это НЕ Java. Включите все теги, относящиеся к вашему вопросу: например, [node.js], [jQuery], [JSON], [ReactJS], [angular], [ember.js], [vue.js], [typescript], [стройный] и т. д.