#javascript #html #css
Вопрос:
Я написал html с 3 переключателями. Каждый переключатель содержится в контейнере div. Я хотел бы, чтобы, если переключатель установлен, фон контейнера div, содержащего отмеченный переключатель, должен стать синим, а фон div, содержащий другие непроверенные переключатели, должен быть белым. Я пытался добиться этого с помощью javascript и css, но это не работает. Не мог бы кто-нибудь, пожалуйста, помочь мне правильно написать этот javascript ?.
<!DOCTYPE html>
<html>
<style>
.stylingForCheckedRadioButton {
color: white;
background-color: blue;
border-style: solid;
border-width: thin;
border-color: grey;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
.stylingForUnCheckedRadioButton {
color: black;
background-color: white;
border-style: groove;
border-width: thin;
border-color: #DCDCDC;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
</style>
<script type="text/javascript">
function checkValue(containerId) {
const rbs = document.querySelectorAll('input[name = "radiobutton"]');
let selectedValue;
for (const rb of rbs) {
if (rb.checked) {
document.getElementById(containerId).style = "stylingForCheckedRadioButton";
}else{
document.getElementById(containerId).style = "stylingForUnCheckedRadioButton";
}
}
};
</script>
<body>
<h1>My Radio Buttons</h1>
<div class="stylingForUnCheckedRadioButton" id="container1">
<input id="radiobuttonId1" type="radio" value="radiobuttonId1" name="radiobutton" onclick="checkValue('container1')">
<label for="radiobuttonId1">Radio button 1</label>
</div>
<div class="stylingForUnCheckedRadioButton" id="container2">
<input id="radiobuttonId2" type="radio" value="radiobuttonId2" name="radiobutton" onclick="checkValue('container3')">
<label for="radiobuttonId2">Radio button 2</label>
</div>
<div class="stylingForUnCheckedRadioButton" id="container3">
<input id="radiobuttonId3" type="radio" value="radiobuttonId3" name="radiobutton" onclick="checkValue('container3')">
<label for="radiobuttonId3">Radio button 3</label>
</div>
</body>
</html>
Комментарии:
1. Вы ищете
className
недвижимость, а неstyle
собственность.
Ответ №1:
таким образом…
const all_Radios = document.querySelectorAll('#container input[type=radio]');
set_Radios() // for page initialization
all_Radios.forEach( btRadio => btRadio.oninput = set_Radios )
function set_Radios()
{
all_Radios.forEach( bt =>
bt.closest('label').classList.toggle('checkedClass', bt.checked))
}
#container > label {
display : block;
color : black;
background-color : white;
border-style : groove;
border-width : thin;
border-color : #DCDCDC;
margin-bottom : 7px;
width : 10%;
height : 2em;
border-radius : 6px;
min-width : 10em;
line-height : 2em;
}
#container > label.checkedClass {
color : white;
background-color : blue;
border-style : solid;
border-color : grey;
}
<h1>My Radio Buttons</h1>
<div id="container">
<label>
<input name="radiobutton" type="radio" value="xxx" >
Radio button 1
</label>
<label>
<input name="radiobutton" type="radio" value="yyy" >
Radio button 2
</label>
<label>
<input name="radiobutton" type="radio" value="zzz" >
Radio button 3
</label>
</div>
Ответ №2:
Вы можете использовать event.target, чтобы получить родительский код элемента ввода для установки стиля classList.replace()
. Каждый щелчок сбрасывает классы родительских элементов на непроверенные, затем, если установлен флажок event.target e.target.checked, замените непроверенный класс на отмеченный класс.
const rbs = document.querySelectorAll('input[name = "radiobutton"]');
// callback function setSel passing in the event from the listener
function setSel(e) {
// get parent element of the event target
let par = e.target.parentNode
// reset each input to unchecked before checking the event target
rbs.forEach(item => item.parentNode.classList.replace('stylingForCheckedRadioButton', 'stylingForUnCheckedRadioButton'))
// if the el is checked we replace the classList with
// the desired class that styles as checked
e.target.checked ?
par.classList.replace('stylingForUnCheckedRadioButton', 'stylingForCheckedRadioButton') :
null
}
// loop over the input nodeList and add event to each node
// in the list with a callback function 'setSel'
rbs.forEach(el => el.addEventListener('click', setSel))
.stylingForCheckedRadioButton {
background-color: red;
}
<!DOCTYPE html>
<html>
<style>
.stylingForCheckedRadioButton {
color: white;
background-color: blue;
border-style: solid;
border-width: thin;
border-color: grey;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
.stylingForUnCheckedRadioButton {
color: black;
background-color: white;
border-style: groove;
border-width: thin;
border-color: #DCDCDC;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
</style>
<script type="text/javascript">
</script>
<body>
<h1>My Radio Buttons</h1>
<div class="container stylingForUnCheckedRadioButton" id="container1">
<input id="radiobuttonId1" type="radio" value="radiobuttonId1" name="radiobutton">
<label for="radiobuttonId1">Radio button 1</label>
</div>
<div class="container stylingForUnCheckedRadioButton" id="container2">
<input id="radiobuttonId2" type="radio" value="radiobuttonId2" name="radiobutton">
<label for="radiobuttonId2">Radio button 2</label>
</div>
<div class="container stylingForUnCheckedRadioButton" id="container3">
<input id="radiobuttonId3" type="radio" value="radiobuttonId3" name="radiobutton">
<label for="radiobuttonId3">Radio button 3</label>
</div>
</body>
</html>
Ответ №3:
Здесь есть две основные проблемы. Во-первых, вы должны использовать className
атрибут вместо style
того, чтобы изменять класс элемента. Во-вторых, в вашей функции JavaScript задает цвет divs на основе последнего значения в rbs
списке узлов. Это означает, что ваш предполагаемый div будет оформлен в соответствии с тем, установлен или нет последний переключатель. Чтобы изменить это, запросите у DOM список всех div, а затем проверьте каждый div в соответствии с соответствующим переключателем на основе индекса.
function checkValue() {
const rbs = document.querySelectorAll('input[name = "radiobutton"]');
rbs.forEach((rb, i) => {
let div = document.getElementById(`container${i 1}`);
div.className = rb.checked ? 'stylingForCheckedRadioButton' : 'stylingForUnCheckedRadioButton';
})
};
.stylingForCheckedRadioButton {
color: white;
background-color: blue;
border-style: solid;
border-width: thin;
border-color: grey;
margin-bottom: 7px;
width: 10%;
min-width: 150px;
height: 50px;
border-radius: 6px;
}
.stylingForUnCheckedRadioButton {
color: black;
background-color: white;
border-style: groove;
border-width: thin;
border-color: #DCDCDC;
margin-bottom: 7px;
width: 10%;
min-width: 150px;
height: 50px;
border-radius: 6px;
}
<!DOCTYPE html>
<html>
<body>
<h1>My Radio Buttons</h1>
<div class="stylingForUnCheckedRadioButton" id="container1">
<input id="radiobuttonId1" type="radio" value="radiobuttonId1" name="radiobutton" onclick="checkValue()">
<label for="radiobuttonId1">Radio button 1</label>
</div>
<div class="stylingForUnCheckedRadioButton" id="container2">
<input id="radiobuttonId2" type="radio" value="radiobuttonId2" name="radiobutton" onclick="checkValue()">
<label for="radiobuttonId2">Radio button 2</label>
</div>
<div class="stylingForUnCheckedRadioButton" id="container3">
<input id="radiobuttonId3" type="radio" value="radiobuttonId3" name="radiobutton" onclick="checkValue()">
<label for="radiobuttonId3">Radio button 3</label>
</div>
</body>
</html>
Ответ №4:
Я рекомендую прочитать некоторые темы на DRY.
// All the radio buttons
const radios = document.querySelectorAll('.radio')
// Function to toggle active class
function handleRadioClick(e) {
// Remove previous active class
for (let i = 0; i < radios.length; i ) {
radios[i].parentNode.classList.remove('active')
}
// Add current active class to parent container
e.target.parentNode.classList.add('active')
}
// Listen for the click event on radios
for (let i = 0; i < radios.length; i ) {
radios[i].addEventListener('click', handleRadioClick, false);
}
.container {
color: black;
background-color: white;
border-style: groove;
border-width: thin;
border-color: #DCDCDC;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
.container.active {
color: white;
background-color: blue;
border-style: solid;
border-width: thin;
border-color: grey;
margin-bottom: 7px;
width: 10%;
height: 50px;
border-radius: 6px;
}
<div class="container">
<input class="radio" id="btn1" type="radio" value="btn1" name="radio">
<label for="btn1">Radio button 1</label>
</div>
<div class="container">
<input class="radio" id="btn2" type="radio" value="btn2" name="radio">
<label for="btn2">Radio button 2</label>
</div>
<div class="container">
<input class="radio" id="btn3" type="radio" value="btn3" name="radio">
<label for="btn3">Radio button 3</label>
</div>