我试图用来自MySQL的数据填充单选按钮。
我希望所选的单选按钮更改颜色,并希望在页面加载时选择第一个元素。
我该怎么做?
<div class="panel bg-product">
<?php
$stmt = mysqli_prepare($link, "SELECT id, name, price FROM products");
$stmt->execute();
$stmt->bind_result($prod_id, $prod_name, $prod_price);
while($stmt->fetch()) {
echo '<label><input type="radio" name="config-prod" value="'.$prod_id.'"> ' .$prod_name.'</label><br>';
}
$stmt->close();
?>
</div>
CSS:
.panel input[type="radio"]:checked + label{
font-weight: 700;
color: red;
transition: color 0.5s ease;
}
此CSS不会在选中时更改单选按钮的颜色,也不会在加载时选择单选按钮。
答案 0 :(得分:0)
这应该为您解决问题。但是您必须注意,它为label
而不是radio
着色,我认为这就是您要实现的目标。
HTML:
<div class="panel">
<input type="radio" name="radios" /><label>R1</label> //label for first Radio
<input type="radio" name="radios" /><label>R2</label> //Label for second radio
</div>
CSS:
.panel input[type="radio"]:checked + label{
background-color: yellow;
width: 10px;
height: 10px;
display: inline-block;
}
在Codepen上测试并可以工作。只需将其用作模板并相应地填充数据即可。刚刚使用一些style
使它在我测试时可见。
答案 1 :(得分:0)
这是您的新CSS:
.input-list {
list-style-type: none;
width: 100%;
padding: 0;
margin: 0;
}
.input-list li input:checked{
content: "";
-webkit-appearance: push-button;
width: 12px;
border-radius: 13px;
height: 12px;
background: red;
}
.input-list li input:checked + label {
color: red;
}
新的JS代码:
document.querySelector("#radio li input").checked = true;
您的新PHP:
<ul id="radio" class="input-list">
<?php
$stmt = mysqli_prepare($link, "SELECT id, name, price FROM products");
$stmt->execute();
$stmt->bind_result($prod_id, $prod_name, $prod_price);
while($stmt->fetch()) {
echo '<li>
<input id="'.$prod_id.'" name="config-prod" value="'.$prod_id.'" type="radio">
<label class="sub-label" for="'.$prod_id.'">'.$prod_name.'</label>
</li>';
}
$stmt->close();
?>
</ul>
这就是它的外观:
document.querySelector("#radio li input").checked = true;
.input-list {
list-style-type: none;
width: 100%;
padding: 0;
margin: 0;
}
.input-list li input:checked {
content: "";
-webkit-appearance: push-button;
width: 12px;
border-radius: 13px;
height: 12px;
background: red;
}
.input-list li input:checked + label {
color: red;
}
<ul id="radio" class="input-list">
<li>
<input id="first" name="radio" value="first" type="radio">
<label class="sub-label" for="first">first</label>
</li>
<li>
<input id="second" name="radio" value="second" type="radio">
<label class="sub-label" for="second">second</label>
</li>
</ul>