我想使用开关盒根据选中的单选按钮获得背景图像。但是,我没有找到正确的解决方案来从选中的单选按钮获取值。
我的代码片段:
HTML:
<section class="configurator__product">
...
</section>
<label for="blue" class="hidden">Blue</label>
<input type="radio" id="blue" name="color-totebag" value="tote-blue" class="circle tote-blue">
<label for="green" class="hidden">Green</label>
<input type="radio" id="green" name="color-totebag" value="tote-green" class="circle tote-green">
<label for="black" class="hidden">Black</label>
<input type="radio" id="black" name="color-totebag" value="tote-black" class="circle tote-black">
有更多的输入,总共 5 个,因此我不认为使用 if/else 是可选的。但我希望我在这里给出的代码量能够让大家清楚地了解这一点。
JavaScript:
const changeTotebagColor = () => {
let totebagColor = document.getElementsByName(`color-totebag`).value;
const $totebagImg = document.querySelector(`.configurator__product`);
switch (totebagColor) {
case `tote-blue`:
$totebagImg.style.backgroundImage = "url('assets/img/totebag_blue')";
case `tote-green`:
$totebagImg.style.backgroundImage = "url('assets/img/totebag_green')";
case `tote-black`:
$totebagImg.style.backgroundImage = "url('assets/img/totebag_black')";
}
}
changeTotebagColor();
我希望我想弄清楚的事情有点清楚。我是 JavaScript 新手,所以也许我做错了。我在网上尝试了很多解决方案,但我没有运气。如果可能的话,我还想避免使用内联 JavaScript,但目前我愿意接受任何解决方案。
最佳答案
正如我在评论中提到的,当您单击事物时,事物的设置方式实际上并没有触发您的函数。您可以在函数之后调用它,但这不会“监视”事物。
您可以通过多种方式解决此问题。最简单的方法是(不更改为 jquery 或其他,并保留你的 vanilla js)简单地将 onclick 应用于你的 radio 。
示例:
<input type="radio" onclick="changeTotebagColor()" id="blue" name="color-totebag" value="tote-blue" class="circle tote-blue">
关于javascript - 如何使用单选按钮和开关盒通过 JavaScript 更改 img?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53419132/