在 HTML 中,我有以下单选按钮选项
o 选择 1
o 选择 2
o 选择 3
我想做的是当有人从上面选择一个单选按钮时,与所选单选按钮对应的文本变为粗体。
因此,例如 - 如果该人选择“选择 2”,则单选按钮选择现在看起来像:
o 选择 1
o 选择 2
o 选择 3
我该怎么做呢?我假设必须使用 JavaScript 或 CSS。
提前致谢
更新:您将如何在不使用 jQuery 的情况下实现“nickf”解决方案?
在 HTML 中,我有以下单选按钮选项
o 选择 1
o 选择 2
o 选择 3
我想做的是当有人从上面选择一个单选按钮时,与所选单选按钮对应的文本变为粗体。
因此,例如 - 如果该人选择“选择 2”,则单选按钮选择现在看起来像:
o 选择 1
o 选择 2
o 选择 3
我该怎么做呢?我假设必须使用 JavaScript 或 CSS。
提前致谢
更新:您将如何在不使用 jQuery 的情况下实现“nickf”解决方案?
您可以纯粹使用 CSS 来做到这一点,但您需要将每个输入的文本包装在 span 或其他标记中:
<input type="radio" name="group1" value="Milk"><span>Milk</span><br>
然后只需使用兄弟选择器:
input[type="radio"]:checked+span { font-weight: bold; }
你可以尝试用 CSS 做所有事情。
我试过了,它有效1:
<input type="radio" name="choice" value="1" checked /><span>First choice</span>
<input type="radio" name="choice" value="2" /><span>Second choice</span>
input[type="radio"]:checked + span
{
font-weight: bold;
}
说明:这会捕获无线电输入 (type="radio") 之后的所有跨度并进行检查。
1我用 Firefox 3 和 IE7 进行了测试,它只适用于 Firefox。(兼容性参考)
我会做这样的事情:
<label><input type="radio" name="myRadio" value="1" /> One</label>
<label><input type="radio" name="myRadio" value="2" /> Two</label>
<label><input type="radio" name="myRadio" value="3" /> Three</label>
在每个元素上使用一个onchange
处理程序来更改父标签的 CSS 类。在 jQuery 中,它看起来像这样:
$(':radio').change(function() { // get all the radio buttons and
// add an onchange handler
var $label = $(this).parent('label'); // get a reference to the parent label
if (this.checked) { // if the radio is on...
$label.addClass('selected'); // add the CSS class "selected" to the label
} else { // otherwise...
$label.removeClass('selected'); // take the class away.
}
});
请记住覆盖标签的默认样式(粗体):
label {
font-weight: normal;
}
label.selected {
font-weight: bold;
}
使用您的 OnChange 事件select
将所选元素的 css 样式更改为粗体。
<input type=button onClick="this.style.fontWeight=bold">
这可能有效,我没有自己测试。当然还有更好的解决方案。
如果您在代码中插入了一个 JavaScript 框架(如jQuery),那么它可能有许多功能可以做同样的事情。选择器、样式器、css 处理程序等等。
我宁愿建议创建一个这样的 CSS 类:
.felkover
{
font-weight: bold;
}
然后只需在任何给定按钮的类属性中添加或删除此定义。
Here is an example :
<script>
function makeBold()
{
var radios = document.getElementsByName("sex");
for (var index = 0; index < radios.length; index++)
{
if (radios[index].checked)
{
document.getElementById("span_" + radios[index].value).style.fontWeight='bold';
}
else
{
document.getElementById("span_" + radios[index].value).style.fontWeight='normal';
}
}
}
</script>
<input type="radio" name="sex" value="male" onclick="makeBold();">
<span id="span_male">Male</span>
<br>
<input type="radio" name="sex" value="female" onclick="makeBold()">
<span id="span_female">Female</span>
EDIT : You should define your text spans with ids like that : span_
有趣的是,您的按钮周围有标签以包含文本,我会将其添加到标签中。
<label onchange="this.parent.children.fontWeight='normal';this.fontWeight='bold';">
虽然理想情况下我不会将此代码内联,而是在页面加载后从头部的某个位置将其连接到它们。