javascript - 使用 JS 或 HTML 更改单选按钮单击时的图像

标签 javascript html css

我有几个单选按钮被图像替换了。我有第二组图像,我希望在选择某个按钮时更改为原始图像。

HTML

<label class="item">
    <input type="radio" value="10" name="size" required="required"/>
    <img src="./images/10.png"/>
</label>
...

CSS

label.item > input {
    visibility: hidden;
    position: absolute;
}

在这种情况下,图像是 10.png。我希望它在选择时更改为 10S.png,但在选择另一个选项时恢复为 10.png

我最好的想法是使用 JS 将 S 附加到图像路径的末尾 onclick,但恢复原状很麻烦。是否有严格的 HTML/CSS 方式来做到这一点,还是必须使用 JS?用于单选按钮的所有图像都是 #.png 从 1-10 的形式,更新的图像是 #S.png 从 1-10(即 2 .png 将变为 2S.png 等)。

如果可能的话,我宁愿不使用 JQuery,我希望有一个浏览器兼容性最好的解决方案。

最佳答案

有一个仅使用 :checked 伪类和伪元素的 HTML 和 CSS 解决方案。

label.item {
  display: inline-block;
  position: relative;
}
label.item > input {
    visibility: hidden;
    position: absolute;
}
label.item > .radio-image::before {
  content: url("http://placehold.it/50x50");
}
label.item > input[type="radio"]:checked + .radio-image::before {
  content: url("http://placehold.it/75x75");
}
<label class="item">
    <input type="radio" value="10" name="size" required="required"/>
    <div class="radio-image"></div>
</label>
<label class="item">
    <input type="radio" value="10" name="size" required="required"/>
    <div class="radio-image"></div>
</label>
<label class="item">
    <input type="radio" value="10" name="size" required="required"/>
    <div class="radio-image"></div>
</label>
<label class="item">
    <input type="radio" value="10" name="size" required="required"/>
    <div class="radio-image"></div>
</label>
<label class="item">
    <input type="radio" value="10" name="size" required="required"/>
    <div class="radio-image"></div>
</label>

据我所知,这在现代浏览器和 IE9+ 中是兼容的

关于javascript - 使用 JS 或 HTML 更改单选按钮单击时的图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31166862/

相关文章:

javascript - 更改禁用按钮的颜色

javascript - 检查所选元素是否包含属性

php - 多维 PHP 数组到 JSON 数组

html - 按钮图像排列跨浏览器顶部的文字?

html - 如何将 svg 放入 span 中并让 span 包围 svg?

具有均匀间距和全宽网格的 CSS 网格元素

javascript - $(document).ready 在插入 _Layout.cshtml 时有效::在插入 Index.cshtml 时无效

javascript - RGBToHex 与 float r、g、b

html - 异步加载图像

html - 名称-值对的语义和结构