繁体   English   中英

如何使此功能更清洁?

[英]How to make this functions cleaner?

我不想每次将新图像添加到 HTML 时都在 JS 代码中添加新行。 但我不知道该怎么做。

$(document).ready(function() {
$('.btn').click(function() {
var bid = $(this).attr('id');
if(bid=="img1" || bid == "img2" || bid == "img3"){
    document.getElementById("img1").style.display = "none";
    document.getElementById("img2").style.display = "none";
    document.getElementById("img3").style.display = "none";
        } else {
            document.getElementById("img4").style.display = "none";
            document.getElementById("img5").style.display = "none";
        }
        document.getElementById(bid).style.display = "block";
    });
});

CSS

.textures {
    background: url("images/room.png") center / cover no-repeat;
    position: static;
    height: 600px;
    width: 800px;
}
div>img {
    display: none;
    position: absolute;
}
[type=radio] {
    position: absolute;
    opacity: 0;
    width: 0;
    height: 0;
}
[type=radio] + img {
    cursor: pointer;
    height: 60px;
    width: 80px
}
[type=radio]:checked + img {
    outline: 2px solid #000;
}

HTML。 在这里,您可以看到如果我单击类别中的半径输入,它将显示来自材料的图像之一。

<!--Room materials-->
<div class="textures">
    <div class="wall">
        <img id="img1" src="images/wall/blue.png" /> 
        <img id="img2" src="images/wall/brick.png" /> 
    </div>

    <div class="floor">
        <img id="img3" src="images/floor/cedro.png" /> 
        <img id="img4" src="images/floor/cipres.png" />
    </div>
</div>

<!--Categories-->
<h5>Walls</h5>
<label>
    <input type="radio" class="btn" id="img1" name="test" value="small" />
    <img src="images/thumbnail/wall/blue.png"/>
</label>
<label>
    <input type="radio" class="btn" id="img2" name="test" value="small" />
    <img src="images/thumbnail/wall/brick.png"/> 
</label>

<h5>Floors</h5>
<label>
    <input type="radio" class="btn" id="img3" name="test" value="small" />
    <img src="images/thumbnail/floor/cedro.png"/> 
</label>
<label>
    <input type="radio" class="btn" id="img4" name="test" value="small" />
    <img src="images/thumbnail/floor/cipres.png"/> 
</label>

这里的例子。

确实是我想要实现的。

首先,在单个文档中有重复的 ID 是无效的 HTML 要将数据放入 HTML 以指示与另一个元素的连接,您可以改用数据属性。 提取数据属性,隐藏所有图像,然后在选择器中使用数据属性:

<input type="radio" class="btn" data-image="img4" name="test" value="small" />
                                ^^^^^^^^^^^^^^^^^
$('.btn').on('change', function() {
  const id = $(this).data('image');
  $('.textures img').hide();
  $('#' + id).show();
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM