首页 > 解决方案 > 如果选中组合单选按钮,如何显示不同的图像?

问题描述

有 4 组单选按钮和显示的室内设计图像。想做演示展示不同饰面的厨房设计。当检查每组饰面(墙壁颜色、橱柜颜色、台面颜色和地板)中的一个按钮时,javascript 代码应该如何显示合适的图像? 截屏

    <div id="nav">
     <legend>Flooring</legend>
      <input type="radio" id="1" name="floor"onClick="changeSrc()"> Boardwalk<br/>
      <input type="radio" id="2" name="floor"onClick="changeSrc()"> Cognac<br/>
      <input type="radio" id="3" name="floor"onClick="changeSrc()"> Java Fossilized<br/>
     <input type="radio" id="4" name="floor"onClick="changeSrc()"> Mocha<br/>
      <input type="radio" id="5" name="floor"onClick="changeSrc()"> Treehouse<br/>
      <input type="radio" id="6" name="floor"onClick="changeSrc()"> Natural<br/><br/>


      <legend>Cabinet</legend>
      <input type="radio" id="7" name="Cabinet"onClick="changeSrc()"> Gray<br/> 
      <input type="radio" id="8" name="Cabinet"onClick="changeSrc()"> Bordeaux<br/>
      <input type="radio" id="9" name="Cabinet"onClick="changeSrc()"> Linen White<br/> 
      <input type="radio" id="10" name="Cabinet"onClick="changeSrc()"> Natural Wood<br/><br/>

      <legend>Wall Color</legend>
      <input type="radio" id="11" name="wall color"> Berkshire Beige<br/> 
      <input type="radio" id="12" name="wall color"> Coastal Fog<br/>
      <input type="radio" id="13" name="wall color"> Linen White<br/> 
      <input type="radio" id="14" name="wall color"> Metropolitan<br/><br/> 

     <legend>Countertop</legend>
      <input type="radio" id="15" name="Countertop"onClick="changeSrc()"> Altair<br/>
      <input type="radio" id="16" name="Countertop"onClick="changeSrc()"> Desert Silver<br/>
      <input type="radio" id="17" name="Countertop"onClick="changeSrc()"> Ironbark<br/>
     <input type="radio" id="18" name="Countertop"onClick="changeSrc()"> Kimbler Mist<br/>
      <input type="radio" id="19" name="Countertop"onClick="changeSrc()"> Mountain Mist<br/>
      <input type="radio" id="20" name="Countertop"onClick="changeSrc()"> Royal Reef<br/><br/>
</div>

    </div>

    <div id="content">
      <img id="myImage" width=1320px src="img/kitchenBoardwalk.jpg"/>
function changeSrc() {
    if (document.getElementById("1").checked & document.getElementById("7").checked & document.getElementById("11").checked & document.getElementById("15").checked) {
    document.getElementById("MyImage").src = "img/kitchenBoardwalk.jpg";
}

标签: javascript

解决方案


在这种情况下,即使在将图像动态分配给src属性之前,预加载图像总是一个好主意。没有这个,浏览器就不能在这样的上下文中实时更新 DOM。

做这个:

var image = new Image();
image.src = 'img/kitchenBoardwalk.jpg';

这应该在changeSrc()声明之前完成。

在您的函数中,更改此行:

document.getElementById("MyImage").src = "img/kitchenBoardwalk.jpg"

至:

document.getElementById("myImage").src = image.src;

请注意,您可以向图像对象/实例添加其他属性,例如高度、宽度、alt等。

希望这可以帮助某人。


推荐阅读